🔻Extracurricular Activity/UMC

[UMC 4기] server 6주차

_니지 2023. 5. 14. 20:34

❗클래스와 객체

  • 학생(Student) 클래스를 작성해보세요. 학생 클래스는 이름(name), 학번(studentID), 전공(major) 멤버 변수를 가지며, 생성자와 정보를 출력하는 메서드를 작성하세요.
  • 학생 객체를 생성하고, 정보를 출력해보세요.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
public class Student {
    private String name;
    private int studentID;
    private String major;
 
    //학생 정보 출력 메소드
    public void printStudent(){
        System.out.println("이름: " + name + ", 학번: " + studentID + ", 전공: " + major);
    }
 
 
    //constructor
    public Student(String name, int studentID, String major) {
        this.name = name;
        this.studentID = studentID;
        this.major = major;
    }
 
    //getter setter
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public int getStudentID() {
        return studentID;
    }
 
    public void setStudentID(int studentID) {
        this.studentID = studentID;
    }
 
    public String getMajor() {
        return major;
    }
 
    public void setMajor(String major) {
        this.major = major;
    }
 
 
}
 
 
-----------------------------------------------------------------------
 
public class Main {
    public static void main(String[] args) {
        Student s1 = new Student("권유진"202021027"컴퓨터정보공학부");
        s1.printStudent();
    }
}
cs

 

 

❗메서드

  • 짝수와 홀수를 구분하는 isEven() 메서드를 작성하세요. 이 메서드는 int형 매개변수를 받아, 짝수인 경우 true, 홀수인 경우 false를 반환합니다.
  • isEven() 메서드를 사용하여, 1부터 10까지의 수 중에서 짝수인 수를 출력해보세요.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Main {
 
    public static boolean isEven(int num){
        if(num % 2 == 0)
            return true;
        else
            return false;
    }
 
    public static void main(String[] args) {
        for(int i = 1; i <= 10; i++){
            if(isEven(i))
                System.out.print(i + " ");
        }
    }
}
cs

 

 

❗예외처리

  • 숫자를 입력받아 10으로 나눈 값을 출력하는 프로그램을 작성하세요.
  • 예외 처리를 이용하여, 0으로 나누려는 경우 "Cannot divide by zero"라는 메시지를 출력하세요.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import java.util.Scanner;
 
public class Main {
 
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();
 
        if(num == 0)
            throw new RuntimeException("Cannot divide by zero");
 
        System.out.println(10 / num);
    }
}
cs

 

728x90
반응형