명품 자바 에센셜 6장 실습 문제

히치키치·2021년 6월 10일
0

1번

다음 main()의 실행 결과 클래스명과 점 값을 연결하여 “MyPoint(3, 20)”이 출력되도록 MyPoint 클래스를 작성하라.

'''
public class MyPoint {

private int x,y;
public MyPoint(int x,int y) {
	this.x=x;
	this.y=y;
}

public String toString() {
	return getClass().getName()+"("+x+","+y+")";
    /*getClass()로 현재 class의 정보 받아오고 
    그 가져온 것에서 getName으로 클래스 이름 받아옴*/
}


public static void main(String[] args) {
	MyPoint mypoint = new MyPoint(3,20);
	System.out.println(mypoint);
    /*Object 클래스 객체 출력하면 toString() 매소드 실행됨*/
}

}
'''

2번

Scanner를 이용하여 한 라인을 읽고, 공백으로 분리된 어절이 몇 개인지 출력을 반복하는 프로그램을 작성하라. “exit”이 입력되면 종료한다.

import java.util.*;
public class two {
	
	public static void main(String[] args) {
		
		Scanner sc=new Scanner(System.in);
		
		while(true) {
			String str=sc.nextLine();
            /* 줄단위/문장 단위로 입력 받기 -> Scanner.nextLine() */
			if(str.equals("exit")) {
				System.out.println("종료합니다.");
				break;
			}
			else {
				StringTokenizer st=new StringTokenizer(str," "); /* StringTokenizer 객체 생성 -> 대상 문자열, 구분문자 */
				int cnt=st.countTokens();
                /* .countTokens로 StringTokenizer 객체 내 token 갯수 */
				System.out.println("어절 개수는 "+cnt);
			}
			
		}
		sc.close();
	}

}

3번

1에서 3까지의 난수를 3개 생성한 뒤 나란히 한 줄에 출력하라. 모두 같은 수가 나올때까지 반복 출력하고, 모두 같은 수이면 “성공”을 출력하고 종료하는 프로그램을 작성하라.

import java.util.*;

public class three {
	
	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		
		while(true) {
			int a=(int)(Math.random()*3+1);
			int b=(int)(Math.random()*3+1);
			int c=(int)(Math.random()*3+1);
			/*Math.random -> int형으로 바꿔줘야함
			 (Math.random()*3+1)로 전체 계산한 것에 대한 int형 적용*/
			
			System.out.println(a+"\t"+b+"\t"+c);
			if(a==b && b==c) {
				System.out.println("성공");
				break;
			}
		}
		sc.close();
		
	}

4번

다음과 같이 +로 연결된 덧셈식을 입력받아 덧셈 결과를 출력하는 프로그램을 작성하라. StringTokenizer와 Integer.parseInt().String의 trim()을 활용하라.

import java.util.*;

public class four {
	
	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		String str=sc.nextLine();
		/*덧셈식 한 줄로 받기*/
		StringTokenizer st=new StringTokenizer(str,"+");
		/*덧셈식 + 기준으로 잘라서 숫자만 객체에 차례로 남겨두기*/
		
		int sum=0;
		while(st.hasMoreTokens()) {
			String st_num=st.nextToken().trim();
			/*nextToken으로 token 한개 받고 딸려오는 이상한 공백은 trim으로 제거*/
			sum+=Integer.parseInt(st_num);
			/*정확하게 숫자 string만 전달된 것 int로 바꿔서 총합 구하기*/
			
		}
		System.out.println("합은 "+sum);
		
		sc.close();
	}

}

5번

다음 코드를 수정하여 Adder 클래스는 util 패키지에, Main 클래스는 app 패키지에 작성하여 응용프로그램을 완성하고 실행시켜라.

package util;

public class Adder {
	
	private int x,y;
	public Adder(int x, int y) {
		this.x=x;
		this.y=y;
	}
	public int add() {
		return x+y;
	}

}
package app;

import util.Adder;
/*util 패키지에 담겨있는 Adder import해오기*/

public class Main {
	
	public static void main(String[] args) {
		Adder adder=new Adder(2,5);
		System.out.println(adder.add());
	}

}

6번

Math.random()의 난수 발생기를 이용하여 사용자와 컴퓨터가 하는 가위바위보 게임을 만들어보자. 가위, 바위, 보는 각각 1, 2, 3 키이다. 사용자가 1, 2, 3, 키 중 하나를 입력하면 동시에 프로그램에서 난수 발생기를 이용하여 1, 2, 3 중에 한 수를 발생시켜 컴퓨터가 낸 것을 결정한다. 그리고 사용자와 컴퓨터 둘 중 누가 이겼는지를 판별하여 승자를 출력한다.

import java.util.*;

public class six {
	
	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		while(true) {
			/*무한 반복으로 입력 받음*/
			System.out.print("가위(1), 바위(2), 보(3), 끝내기(4) >>");
			int user=sc.nextInt();
			int com=(int)(Math.random()*3+1);
			
		
			if(user==4) {
				System.out.println("게임종료");
				break;
			}
			/*종료 key 4에 대해는 switch case 안에 들어가서 처리 x
			 무한 반복을 멈추는 것이므로 while 안에서 처리되게!!*/
			
			switch(user) {
				case 1:{ //사용자가 가위 낸 경우
					System.out.print("사용자 가위 : ");
					if(com==1) {System.out.println("컴퓨터 가위\n비겼습니다.");}
					else if(com==2) {System.out.println("컴퓨터 바위\n졌습니다.");}
					else {System.out.println("컴퓨터 보\n이겼습니다.");}
					break;
				}
				case 2:{//사용자가 바위 낸 경우
					System.out.print("사용자 바위 : ");
					if(com==2) {System.out.println("컴퓨터 바위\n비겼습니다.");}
					else if(com==3) {System.out.println("컴퓨터 보\n졌습니다.");}
					else {System.out.println("컴퓨터 가위\n이겼습니다.");}
					break;
				}
				case 3:{ //사용자가 보를 낸 경우
					System.out.print("사용자 보 : ");
					if(com==3) {System.out.println("컴퓨터 보\n비겼습니다.");}
					else if(com==1) {System.out.println("컴퓨터 가위\n졌습니다.");}
					else {System.out.println("컴퓨터 주먹\n이겼습니다.");}
					break;
				}
				

			}

		}
		
		sc.close();
	}

}

Bonus 1

중심을 표현하는 int 타입의 x, y 필드와, 반지름 값을 저장하는 int 타입의 radius 필드를 가진 Circle 클래스를 작성하고자 한다. 생성자는 x, y, radius 값을 인자로 받아 필드를 초기화하고, equals() 메소드는 면적이 같으면 두 Circle 객체가 동일한 것으로 판별한다. 아래는 Circle 클래스와 이를 활용하는 코드의 실행 결과이다. 빈칸을 채워라.

class Circle{
	private int x,y,radius;
	public Circle(int x, int y, int radius) {
		this.radius=radius;
		this.x=x;
		this.y=y;
	}
	
	public String toString() {
		/*Object가 String과 연산되거나 출력 될 때 오버라이딩*/
		return "("+x+","+y+")"+" 반지름 "+radius;
	}
	
	public boolean equals(Object obj) {
    /*객체끼리 내용 동일한지 equals 오버라이딩*/
		Circle c=(Circle) obj;
		if (Math.pow(radius,2)*Math.PI==Math.pow(c.radius, 2)*Math.PI)
			return true;
		else return false;
	}
}


public class bonus_1 {
	public static void main(String[] args) {
		Circle a=new Circle(1,2,10);
		Circle b= new Circle(5,6,10);
		System.out.println("원 1"+a);
		System.out.println("원 2"+b);
		if(a.equals(b)) System.out.println("같은 원입니다.");
		else System.out.println("다른 원입니다.");
		
	}

}

bonus 2

StringBuffer 클래스를 이용하여 사용자로부터 영문 한 줄을 입력받고, 글자 하나만 랜덤하게 선택하여 다른 글자로 수정하여 출력하는 프로그램을 작성하라. 공백도 수정에 포함한다.

0개의 댓글