프로그래밍 언어/javastudy

명품 Java Essential 6단원 Bonus 1 ~ 3

fladi 2021. 7. 16. 01:52
728x90

교재: 명품 자바 에센셜

 

<Bonus 1 Circle클래스 활용>

class Circle {
	private int x, y, radius;
	public Circle(int x, int y, int radius) {
		this.x = x; this.y = y; this.radius = radius;
	}
	public String toString() {
		return "(" + x +", " + y + ") 반지름 " + radius;
	}
	@Override
	public boolean equals(Object obj) {	
		if (((Circle)obj).radius == radius) return true;
		else return false;
	}
}

public class CircleManager {
	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("다른 원입니다.");
	}
}

equals메소드에 2줄로 쑤셔넣으라길래 어거지로 넣어봤는데 마음에 안드네요.

 

@Override
public boolean equals(Object obj) {
	Circle c = (Circle)obj;
		
	if (c.radius == radius) 
		return true;
	else 
		return false;
}

이렇게 쓰는게 훨씬 보기도 편하고 깔끔한 것 같습니다.

 

 

 

<Bonus 2 글자 하나를 랜덤하게 선택하여 다른 글자로 수정>

public class Modify {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		while(true) {
			System.out.print(">>");
			String s = scanner.nextLine();
			StringBuffer sb = new StringBuffer(s);
			if (sb.toString().equals("exit")) {
				System.out.println("종료합니다...");
				break;
			}
			int index = (int)(Math.random()*s.length());
			while(true) {
				int i = (int)(Math.random()*26);
				char c = (char)('a'+i);
				if (sb.charAt(index) != c) {
					sb.replace(index, index+1, Character.toString(c));
					break;
				}	
			}
			System.out.println(sb);	
		}
		scanner.close();
	}
}

빈칸은 어떻게 잘 채운 것 같은데 안보고 만드려고 하면 힘들 것 같습니다.

안보고 만들어보는 연습도 해봐야겠습니다.

 

 

 

<Bonus 3 문자열 회전 출력 프로그램>

import java.util.Scanner;

public class StringRotate {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		
		System.out.println("문자열을 입력하세요. 빈 칸 있어도 되고 영어 한글 모두 됩니다.");
		String text = scanner.nextLine();
		
		System.out.println("<Enter>를 입력하면 문자열이 한 글자씩 회전합니다.");
		
		while(true) {
			String key = scanner.nextLine();
			if (key.equals("")) {
				String first = Character.toString(text.charAt(0));
				String last = text.substring(1);
				text = last.concat(first);
				System.out.print(text + " >>");
			}
			else if (key.equals("q"))
				break;
			else
				System.out.print(text + " >>");
		}
		System.out.println("종료합니다...");
		
		scanner.close();
	}
}

처음에는 key입력을 scanner.next()로 받아서 계속 동작이 안됐습니다 ㅜㅜ

next로는 공백문자를 입력받을 수 없는 것 같더라고요. (문자열을 공백문자로 구분하기 때문인 것 같습니다)

저기서 꼭 nextLine()메소드를 사용해줘야합니다!

728x90