ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • TIL #9 - 필드, 메소드
    프로그래밍/TIL(국비과정) 2020. 4. 7. 19:14

     

    # 필드 

    필드는 위치에 따라 호출 방법이 다르다. 

    class VariableTest2 {
    	int a; // 필드, 초기화 완료(0으로) 
    	static int b; // 필드, 초기화 
    
    	public static void main(String[] args) {
    		int a = 10;  // local variable(지역변수), garbage(쓰레기값)
    		System.out.println("a =" + a);
    		
    		// 필드 a값 부르기 
    		System.out.println("필드 a =" + new VariableTest2().a);
    		
            // 필드 b값 부르기 
    		System.out.println("필드 b = " + VariableTest2.b);
    	}
    }

    - 전역변수 

    main 메서드 밖에 선언된 필드 int a와 static int b가 전역변수이다. 

    해당 필드값을 부르기 위해서는 위치가 어딘지 정확하게 알려주어야한다. 

    그렇기 때문에 new VariableTest2()와 VariableTest2를 붙여주었다. 

    static이 붙은 b의 경우에는 new를 붙여줄 필요없이 사용이 가능하다. 

    - 지역변수 

    지역변수는 메서드 안에서 선언되는 필드를 말한다. 

    int a = 10; 의 위치를 보면 main 메서드 내에서 선언되었다. 

    그렇기 때문에 전역변수와 같이 위치를 알려줄 필요가 없다. 

     


    #메서드 

    메서드는 명령어들의 집합이다. 

    메서드에서 구현을 하고 메인 메소드 안에서 구현한 것을 호출하는 식으로 사용한다.

    주의할 점은 메서드는 메서드 안에 쓰면 안된다. 

    (main 메서드 안에 다른 메서드를 만들 수 없다는 것이다) 

     

    class MethodTest {
    
    	public void disp() { // 구현
    		System.out.println("non-static 메소드");
    	}
    	public static void print() { // 구현
    		System.out.println("static 메소드");
    	}
    
    	public static void main(String[] args) {
    		// 구현한 것을 호출 
    		// new MethodTest().disp();
    		MethodTest.print();
    
    		MethodTest aa = new MethodTest(); // 객체 
    		System.out.println("객체 aa = " + aa); // aa의 참조값 
    		System.out.println("객체 aa = " + aa.toString()); // 현재 주소를 문자열로 바꿔서 찍어라 
    		System.out.println("객체 aa = " + aa.hashCode()); // 주소를 10진수로 
    		aa.disp();
    
    	}
    }
    

     

    각 메서드를 보면 static이 있는 것과 없는 것이 있다. 

    static이 없는 disp의 메서드는 호출하기 위해서 MethodTest 객체를 만들어 객체 이름으로 위치를 알려주고 호출했다. 

    static이 붙은 print 메서드는 객체를 만들어 굳이 new를 붙이지 않아도 호출되는 것을 확인할 수 있다. 

    (하지만 위치는 알려줬다 )

     

    # 메소드 연습을 위한 사칙연산 프로그램

    class MethodTest2 {
    	int a; 
    
    	public static void main(String[] args) {
    		MethodTest2 mt = new MethodTest2();
    		System.out.println("합 = " + mt.sum(25,36)); // 호출 
    		System.out.println("차 = " + mt.sub(25,36));
    		System.out.println("곱 = " + mt.mul(25,36));
    		System.out.println("몫 = " + mt.div(25,36));
    	}
    	// 구현
    	public int sum(int a, int b) {
    		return a + b; // 반환 
    	}
    
    	public int sub(int a, int b){
    		return a-b;
    	}
    
    	public int mul(int a, int b) {
    		return a * b; 
    	}
    
    	public double div(int a, int b) {
    		return (double)a/b;
    		// 오버로딩 때문에 매개변수에 double 적어주지말고 
    		// return 받는 값을 형변환 시켜주자
    	}
    }

     

    사칙연산 메소드 모두 static이 붙지 않았기 때문에 객체를 생성해 그 객체 이름으로 위치를 정확히 붙혀 호출한 것을 확인 할 수 있다. 

    여기서 나누기를 하는 div 메소드의 경우 조금 신경써야할 것이 있는데 

    나누기의 경우 int 형 보다는 double형의 값이 나오는 것을 선호해 

    리턴 타입을 double로 했다. 

    하지만 여전히 a와 b는 int값이기 때문에 int 값이 리턴되는데 

    이럴 경우엔 리턴값을 double로 형변환 해준다. 

    나는 여태껏 매개변수 중 하나를 double 형으로 설정했는데 

    오버로딩 때문에 (기능은 같지만 매개변수의 타입이 다른 메서드) 좋지 않은 방법이라고 한다. 

     

    # Java에서 만들어준 class를 불러오는 import

    난수를 만들고 싶을 때, 

    그렇게 힘들게 코드를 짤 필요가 없다. 

    Java에서 이미 만들어준 class의 메서드가 있기 때문이다. 

    import java.util.Random;
    
    class MethodTest3 {
    	public static void main(String[] args) {
    		System.out.println("큰 값 :: " + Math.max(25, 36));
    
    		// 2의 5승 계산 : 32
    		double power = Math.pow(2, 5);
    		System.out.println("제곱 :: " + (int)power);
    
    		// 난수 > 컴퓨터가 불규칙하게 발생하는 수, 0 < 난수 <= 1
    		int a;
    		a = (int)(Math.random() * 100); // 0 ~ 99.xxx 
    
    		System.out.println(a);
    
    		Random random = new Random();
    		double b; 
    		b = random.nextDouble();
    		System.out.println(b);
    				
    	}
    }

    바로 java.lang에 들어있는 Math 클래스의 메서드들이다. 

     

    먼저 두 값 중 가장 큰 값을 골라주는 max 메서드이다. 

    max 메서드는 Math 라는 클래스 안에 있는 메서드이다. 

    그렇기 때문에 사용할 때 Math.max 의 형태가 되는 것이다. 

    그 아래의 제곱승을 구하는 pow 메서드와 난수를 구해주는 random 메서드도 마찬가지다. 

    모두 Math라는 class에서 호출된 메서드들이다. 

    이는 메서드의 호출이기 때문에 import가 필요없었지만 

     

    맨 위에 보면 import java.util.Random; 이라고 적혀 있는데 

    이는 java에 util이라는 패키지에서 Random이라는 클래스를 가져온 것이다. 

    이 경우엔 import가 필요하다. 

    또, Random의 경우엔 static가 없기 때문에 객체를 생성해줘야한다. 

     

    메서드를 호출하는 경우에는 import를 하지 않는다. 

    JVM(Java Virtual Machine)에서 알아서 인식을 하기 때문이다. 

    하지만 클래스의 경우에는 모르기 때문에 import코드를 통해 가지고 와야한다 

     

     

    # 성적 프로그램

    위에서 배운 것들을 총망라해서 이름, 국영수 성적을 입력받아 총점과 평균을 구하는 프로그램을 만들어본다. 

     

    먼저 main 메서드 안에서 각종 입력을 받는다. 

    		System.out.print("이름 입력 : ");
    		String name = scan.next(); 
    
    		System.out.print("국어점수 입력 : ");
    		int korScore = scan.nextInt();
    		System.out.print("영어점수 입력 : ");
    		int engScore = scan.nextInt();
    		System.out.print("수학점수 입력 : ");
    		int mathScore = scan.nextInt();

     

    그런 후 main 메서드를 나가 총점, 평균, 출력 메서드를 만들어본다. 

    먼저 총점 메서드이다. 

    // 총점 메소드 
    	public int calcTot(int korScore, int engScore, int mathScore){
    		return korScore + engScore + mathScore;
    	}

    그대로 입력받은 국영수 점수를 더한 값을 return 해주면 된다. 

    (연습을 위해서 static을 붙이지 않았다)

     

    다음은 평균 메서드이다. 

    public double calcAvg(int tot){
    		return tot/3.0;
    	}

    메서드들을 전부 만들고 나면 다시 main 메서드에 가서 총점 tot과 평균 avg 변수에 대한 설정을 추가적으로 더 한다.

    여하튼 평균 메서드에서 매개변수로 총점 tot를 받아 그대로 국영수 3과목 수를 나눈다. 

    단 double 값을 받을 것이기 때문에 3이 아닌 3.0으로 나눈다. 

     

    출력 메서드이다. 

    	public void print(String name, int korScore, int engScore, int mathScore, int tot, double avg){
    
    		System.out.println("\t*** " + name + " 성적표 ***\t");
    		System.out.print("국어\t영어\t수학\t총점\t평균\n");
    		System.out.print(korScore+"\t"
    						+engScore+"\t"
    						+mathScore+"\t"
    						+tot+"\t"
    						+ String.format("%.2f", avg)); // %d : 10진수
    	}

     배열을 사용하지 않는 전제 이기 때문에..

    일일이 매개변수를 나열했다.

    입력받는 값들이다. 이름, 국영수 점수, 그리고 총점과 평균.

     

    그런 후 다시 main 메서드로 돌아간다. 

    위에서 만든 세개의 메서드 모두 static이 없기 때문에 우리는 객체를 생성해주어야한다. 

    public static void main(String[] args) {
    		Scanner scan = new Scanner(System.in);
    		SungJuk sj = new SungJuk();

    이 밑으로 위에서 입력한 사용자로부터 입력 코드를 넣고 

    수학점수 입력까지 끝나면 총점과 평균 메서드를 호출한다. 

    		int tot = sj.calcTot(korScore, engScore, mathScore); // 호출 
    		double avg = sj.calcAvg(tot);

    어떤 값들을 받을 것인지, 또 메서드의 위치는 어딘지에 대한 것들이다. 

    그런 후 출력 메서드를 호출한다. 

    sj.print(name, korScore, engScore, mathScore, tot, avg);

     

     

    아래는 전체적인 코드이다. 

    // 이름, 국어, 영어, 수학 점수를 입력 받아서 총점과 평균 
    import java.util.Scanner;
    
    class SungJuk{
    	// 총점 메소드 
    	public int calcTot(int korScore, int engScore, int mathScore){
    		return korScore + engScore + mathScore;
    	}
    
    	// 평균 메소드 
    	public double calcAvg(int tot){
    		return tot/3.0;
    	}
    	
    	// 출력 메소드 
    	public void print(String name, int korScore, int engScore, int mathScore, int tot, double avg){
    
    		System.out.println("\t*** " + name + " 성적표 ***\t");
    		System.out.print("국어\t영어\t수학\t총점\t평균\n");
    		System.out.print(korScore+"\t"
    						+engScore+"\t"
    						+mathScore+"\t"
    						+tot+"\t"
    						+ String.format("%.2f", avg)); // %d : 10진수
    	}
    
    
    	public static void main(String[] args) {
    		Scanner scan = new Scanner(System.in);
    		SungJuk_new sj = new SungJuk_new();
    
    		System.out.print("이름 입력 : ");
    		String name = scan.next(); // nextLine : 엔터값 먹음
    
    		System.out.print("국어점수 입력 : ");
    		int korScore = scan.nextInt();
    		System.out.print("영어점수 입력 : ");
    		int engScore = scan.nextInt();
    		System.out.print("수학점수 입력 : ");
    		int mathScore = scan.nextInt();
    
    		int tot = sj.calcTot(korScore, engScore, mathScore); // 호출 
    		double avg = sj.calcAvg(tot);
    		
    		sj.print(name, korScore, engScore, mathScore, tot, avg);
    
    	}
    }

     

    댓글

Designed by Tistory.