언어/[Java]

[Java] 명품 자바 프로그래밍 2장 실습문제

dayeonsheep 2023. 7. 29. 19:10

1번

package Study;
import java.util.*;

public class Sample {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		System.out.println("2자리수 정수 입력(10~99)>>>");
		int num = sc.nextInt();
		
		if (num/10 == num%10) {
			System.out.println("Yes 10의 자리와 1의 자리 같습니다.");
		}
		else {
			System.out.println("no~ fail");
		}
	}
}

2번

package Study;
import java.util.*;

public class Sample {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		System.out.println("원화를 입력하세요(단위 원)>>>");
		int won = sc.nextInt();
		float dlr = won/1100;
	
		System.out.printf(+won+"원은 $"+dlr+"입니다.");
	}
}

3번

package Study;
import java.util.*;

public class Sample {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		System.out.println("금액 입력 >>>");
		int money = sc.nextInt();
		int [] change = {50000,10000,1000,100,50,10,1};
		
		for(int i=0; i<change.length; i++) {
			System.out.println(change[i]+"원권 "+money/change[i]);
			money %= change[i];
		}	
	}
}

if 문으로 노가다 하다가 구린 것 같아서 배열로 풀음

 

4번

package Study;
import java.util.*;

public class Sample {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		System.out.println("정수 3개 입력>> ");
		int n1 = sc.nextInt();
		int n2 = sc.nextInt();
		int n3 = sc.nextInt();
		
		if((n1>n2 && n2>n3) || (n3>n2 && n2>n1)) {
			System.out.println("중간값은 "+n2);
		}
		else if((n3<n1 && n1<n2) || (n2<n1 && n1<n3)) {
			System.out.println("중간값은 "+n1);
		}
		else {
			System.out.println("중간값은 "+n3);
		}
	}
}

if elseif 문에서 앞 조건식만 썼다가

n2가 중간값인거 보면 n3에 젤 큰 게 올 수도 있고 n1에 젤 큰 게 올 수도 있는데 암튼 그래서 절케 바꿈

 

배열로 받아서 max, min함수 써서 비교해볼까 했는데 차라리 얘가 더 간단한 것 같아서 일케 짬

 

5번

package Study;
import java.util.*;

public class Sample {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		System.out.println("정수 3개 입력>> ");
		int n1 = sc.nextInt();
		int n2 = sc.nextInt();
		int n3 = sc.nextInt();
		
		if (n1+n2>n3 || n2+n3>n1 || n1+n3>n2) {
			System.out.println("삼각형 가능 ");
		}
		else {
			System.out.println("안됨~");
		}
	}
}

 

문제 조건대로만 풀면 이렇게인데 이러면 다 됨 0이 입력되지 않는 이상ㅋㅋ

문제 조건이 잘못됨

삼각형 변 길이 조건은 :가장 긴 변의 길이가 다른 두 변 길이의 합보다 작아야 됨

 

package Study;
import java.util.*;

public class Sample {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		System.out.println("정수 3개 입력>> ");
		int n1 = sc.nextInt();
		int n2 = sc.nextInt();
		int n3 = sc.nextInt();
		
		if (n1>n2 && n1>n3) {
			if(n1<n2+n3) {System.out.println("삼각형 가능 ");}
			else {System.out.println("no");}
			}
		else if(n2>n1 && n2>n3) {
			if(n2<n1+n3) {System.out.println("삼각형 가능 ");}
			else {System.out.println("no");}
			}
		else if(n3>n1 && n3>n2) {
			if(n3<n1+n2) {System.out.println("삼각형 가능 ");}
			else {System.out.println("no");}
		}
		else {
			System.out.println("go back...");
		}
	}
}

근데 또 변 길이 같으면 이 조건 안됨 귀찮으니 돌아가라고 go back else에게 맡겨주고

조건이 너무 부족함

 

 

6번

package Study;
import java.util.*;

public class Sample {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		System.out.println("정수 입력>> ");
		int num = sc.nextInt();
		int num10 = num/10;
		int num1 = num%10;
		
		int clapcnt = 0;
		
		if(num1%3 == 0 && num1%3!=0) {
			clapcnt++;
		}
		if(num10%3 == 0 && num10%3!=0) {
			clapcnt++;
		}
		
		if(clapcnt == 2) {
			System.out.println("박수 짝짝 ");
		}
		else if(clapcnt == 1) {
			System.out.println("박수 짝 ");
		}
	}
}

얜 첨에 대충 짰다가 1의 자리 넣으면 틀리길래 고침

--> %3 !=0 이면 일의 자리 수 넣었을 때 틀리는 거 고칠 수 있었음

 

근데 출력이...

근데 if문 저렇게 있는 거 맘에 안듦

변수 선언도 넘 많이 했나 싶고 더 깔끔하게 못 풀까

 

package Study;
import java.util.*;

public class Sample {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		System.out.println("정수 입력>> ");
		int num = sc.nextInt();
		int clapcnt = 0;
		
		if((num/10)%3==0 && (num/10)!=0) {
			clapcnt++;
		}
		if((num%10)%3==0 && (num%10)!=0) {
			clapcnt++;
		}
		if(clapcnt==0) {
			System.out.println(num);
		}
		else{
			if(clapcnt == 2) {
				System.out.println("박수 짝짝 ");
			}
			else {
				System.out.println("박수 짝 ");
			}
		}
	}
}

음...

뭐가 더 나은지는 모르겠당

 

7번

package Study;
import java.util.*;

public class Sample {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		System.out.println("좌표 입력>> ");
		int x = sc.nextInt();
		int y = sc.nextInt();
		
		if( x>=100 && x<=200 && y>=100 && y<=200) {
			System.out.println("("+x+","+y+")는 사각형 안에 있음. ");
		}
		else {
			System.out.println("없으~ ");
		}
	}
}

 

8번

package Study;
import java.util.*;

public class Sample {
	public static boolean inRect(int x, int y) {
	    if((x >= 100 && x <= 200) && (y >= 100 && y <= 200))
	        return true;
	     else
	        return false;
	}
	
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.print("좌표 2개 차례대로 입력>>");
        int x1 = sc.nextInt();
        int y1 = sc.nextInt();

        int x2 = sc.nextInt();
        int y2 = sc.nextInt();

        boolean rect1 = inRect(x1, y1);
        boolean rect2 = inRect(x2, y2);

        if(rect1==true || rect2==true){
            System.out.println("충돌");
        } else System.out.println("충돌 안함 ");
		
	}
}

힌트로 준 거 응용해서 함

저렇게 클래스 2개 해서 첨 써봄

근데 이렇게 한 코드 안에서 잘 안쓴다카던데 암튼

 

9번

package Study;
import java.util.*;

public class Sample {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		System.out.println("원 중심 좌표랑 반지름 입력 >> ");
		int x1 = sc.nextInt();
		int y1 = sc.nextInt();
		double r = sc.nextDouble();
		
		System.out.println("점 입력 >> ");
		int x2 = sc.nextInt();
		int y2 = sc.nextInt();
		
		double distance = Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y2-y2));

        if(distance<r)  System.out.println("점 ("+x2+", "+y2+")는 원 안에 있다.");
        else    System.out.println("점 ("+x2+", "+y2+")는 원 안에 없다.");
		
	}
}

힌트 보고 함

 

10번

원의 중심끼리의 거리가 반지름보다 합친것끼리보다 작으면 겹침

package Study;
import java.util.*;

public class Sample {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		System.out.print("첫번째 원의 중심과 반지름 입력>>");
        int x1 = sc.nextInt();
        int y1 = sc.nextInt();
        double r1 = sc.nextDouble();

        System.out.print("두번째 원의 중심과 반지름 입력>>");
        int x2 = sc.nextInt();
        int y2 = sc.nextInt();
        double r2 = sc.nextDouble();

        double distance = Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));

        if(distance>r1+r2)  System.out.println("두 원은 서로 겹치지 않는다.");
        else System.out.println("두 원은 서로 겹친다.");
	}
}

 

11번

기존 문법으로 다 푸는 건 넘 노가다 같아서

새로운 switch 문법을 써볼겸

package Study;
import java.util.*;

public class Sample {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		System.out.println("달 입력>>");
		int num=sc.nextInt();
		
		switch(num) {
			case 3, 4, 5 -> {System.out.println("봄");
				break;}
			case 6, 7, 8 -> {System.out.println("여름");
				break;}
			case 9, 10, 11 -> {System.out.println("가");
				break;}
			case 12, 1, 2 -> {System.out.println("겨울");
				break;}
		default -> System.out.println("잘못입력");		
		}
	}
}

여기서 case 문에서 print문이랑 break문 수행할 게 2문장 이상이니까 중괄호로 묶어줘야 됨

안그럼 오류남

default처럼 한 문장이면 ㄱㅊ

 

12번

package Study;
import java.util.*;

public class Sample {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		System.out.println("연산 >>");
		Double n1 = sc.nextDouble();
		String op = sc.next();
		Double n2 = sc.nextDouble();
		int res=0;
		
		if(op.equals("+"))
			res=(int) (n1+n2);
		else if(op.equals("-"))
			res=(int) (n1-n2);
		else if(op.equals("*"))
			res=(int) (n1*n2);
		else if(op.equals("/")) {
			if(n2==0) {
				System.out.print("0으로 나눌 수 없습니다.");
				return;
			}
			else
				res=(int) (n1/n2);
			}
		else {
			System.out.print("no");
			return;
		}
		System.out.println(n1+op+n2+"의 계산결과는"+res);
	}
}

문제에서 실수로 받으라는데 출력할 땐 정수로 나오길래 (int) 형변환 함

근데! 이렇게 하면 0으로 나눌 때 계산결과도 같이 출력됨

package Study;
import java.util.*;

public class Sample {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		System.out.println("연산 >>");
		Double n1 = sc.nextDouble();
		String op = sc.next();
		Double n2 = sc.nextDouble();
		int res=0;
		
		out:
		if(op.equals("+"))
			res=(int) (n1+n2);
		else if(op.equals("-"))
			res=(int) (n1-n2);
		else if(op.equals("*"))
			res=(int) (n1*n2);
		else if(op.equals("/")) {
			if(n2!=0) {
				res=(int) (n1/n2);
			}
			else
				System.out.print("0으로 나눌 수 없습니다.");
				break out;
			}
		else {
			System.out.print("no");
			return;
		}
		System.out.println(n1+op+n2+"의 계산결과는"+res);
	}
}

if문에서도 label 되나? 했더니 코드 쓸 때는 오류 안나는데

run하니까 

연산 >>

2+4

Exception in thread "main" java.util.InputMismatchException

at java.base/java.util.Scanner.throwFor(Scanner.java:939)

at java.base/java.util.Scanner.next(Scanner.java:1594)

at java.base/java.util.Scanner.nextDouble(Scanner.java:2564)

at Study.Sample.main(Sample.java:9)

 

이런 오류가 나네요 

inputmismatch랜다

package Study;
import java.util.*;

public class Sample {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		System.out.println("연산 >>");
		Double n1 = sc.nextDouble();
		String op = sc.next();
		Double n2 = sc.nextDouble();
		int res=0;
		
		if(op.equals("+")) {
			res=(int) (n1+n2);
			System.out.println(n1+op+n2+"의 계산결과는 "+res);
		}
		else if(op.equals("-")) {
			res=(int) (n1-n2);
			System.out.println(n1+op+n2+"의 계산결과는 "+res);
		}
		else if(op.equals("*")) {
			res=(int) (n1*n2);
			System.out.println(n1+op+n2+"의 계산결과는 "+res);
		}
		else if(op.equals("/")) {
			if(n2!=0) {
				res=(int) (n1/n2);
				System.out.println(n1+op+n2+"의 계산결과는 "+res);
			}
			else
				System.out.print("0으로 나눌 수 없습니다.");
			}
		else {
			System.out.print("no");
			return;
		}
	}
}

그냥 얌전히 노가다 함