본문으로 바로가기

[Chapter 2_실습문제]

category withTextBook/명품 JAVA 프로그래밍 2021. 4. 12. 20:33

1. Scanner 클래스를 이용하여 원화를 입력받아 달러로 바꾸어 다음 예시와 같이 출력하는 프로그램을 작성하라.

1. $1=1100원으로 가정하고 계산하라.

 

import java.util.Scanner;

public class WonToDollar {

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

2. Scanner 클래스를 이용하여 2자리의 정수(10~99사이)를 입력받고, 10의 자리와 1의 자리가 같은지 출력하는 프로그램을 작성하라.

 

import java.util.Scanner;

public class DigitOfOneAndTen {

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

3. Scanner 클래스를 이용하여 정수로 된 돈의 액수를 입력받아

3. 오만 원권, 만 원권, 천 원권, 500원짜리 동전, 100원짜리 동전, 50원짜리 동전, 10원짜리 동전, 1원짜리 동전 각 몇 개로 변환되는지

3. 출력하라.

 

import java.util.Scanner;

public class ChangeMoney {

	public static void main(String[] args) {
    
		Scanner scanner = new Scanner(System.in);
		
        
		System.out.print("금액을 입력하시오>>");
		int price = scanner.nextInt();
		
        
		int oman = price / 50000;
		int man = (price % 50000) / 10000;
		int chun = (price % 10000) / 1000;
		int obaek = (price % 1000) / 500;
		int baek = (price % 500) / 100;
		int osib = (price % 100) / 50;
		int sib = (price % 50) / 10;
		int il = price % 10;
		
        
		if (oman != 0) System.out.println("오만원권 " + oman + "매");
		if (man != 0) System.out.println("만원권 " + man + "매");
		if (chun != 0) System.out.println("천원권 " + chun + "매");
		if (obaek != 0) System.out.println("오백원 " + obaek + "개");
		if (baek != 0) System.out.println("백원 " + baek + "개");
		if (osib != 0) System.out.println("오십원 " + osib + "개");
		if (sib != 0) System.out.println("십원 " + sib + "개");
		if (il != 0) System.out.println("일원 " + il + "개");
		
        
		scanner.close();
	}
}

4. Scanner 클래스로 정수 3개를 입력받고 3개의 숫자 중 중간 크기의 수를 출력하라. 평균값을 구하는 것이 아님에 주의하라.

 

import java.util.Scanner;

public class MiddleNum {

	public static void main(String[] args) {
    
		Scanner scanner = new Scanner(System.in);
		
        
		System.out.print("정수 3개 입력>>");
		int a = scanner.nextInt();
		int b = scanner.nextInt();
		int c = scanner.nextInt();
		int middle = 0;
		
        
		if (a > b) {
			if (b > c)
				middle = b;
			else {
				if (a > c)
					middle = c;                  
				else
					middle = a;
			}
		}
        
		else {
			if (c > b)
				middle = b;     
			else {
				if (a > c)
					middle = a;                   
				else
					middle = c;
			}
		}
		
        
		System.out.println("중간 값은 " + middle);
		
        
		scanner.close();
	}
}

5. Scanner를 이용하여 삼각형의 변의 길이를 나타내는 정수를 3개 입력받고 이 3개의 수로 삼각형을 만들 수 있는지 판별하라.

5. 삼각형이 되려면 두 변의 합이 다른 한 변의 합보다 커야 한다.

 

import java.util.Scanner;

public class PossibleTriangle {

	public static void main(String[] args) {
    
		Scanner scanner = new Scanner(System.in);
		
        
		System.out.print("정수 3개 입력>>");
		int a = scanner.nextInt();
		int b = scanner.nextInt();
		int c = scanner.nextInt();
		int max = 0, medium = 0, min = 0;
		
        
		if (a > b) {			
			if(b > c) {
				max = a;
				medium = b;
				min = c;
			}
			else {
				if (a > c) {
					max = a;
					medium = c;
					min = b;
				}
				else {
					max = c;
					medium = a;
					min = b;
				}
			}
		}
		else {
			if (c > b) {
				max = c;
				medium = b;
				min = a;
			}
			else {
				if (a > c) {
					max = b;
					medium = a;
					min = c;
				}
				else {
					max = b;
					medium = c;
					min = a;
				}
			}
		}
		
        
		if (max < medium + min)
			System.out.println("삼각형이 됩니다.");
		
        
		scanner.close();
	}
}

6. 369게임을 간단히 작성해보자.

6. 1~99까지의 정수를 입력받고 정수에 3, 6, 9 중 하나가 있는 경우는 "박수짝"을 출력하고

6. 두 개 있는 경우는 "박수짝짝"을 출력하는 프로그램을 작성하라.

6. 예를 들면, 키보드로 입력된 수가 13인 경우 "박수짝"을, 36인 경우 "박수짝짝"을 출력하면 된다.

 

import java.util.Scanner;

public class ThreeSixNineGame {

	public static void main(String[] args) {
    
		Scanner scanner = new Scanner(System.in);
		
        
		System.out.print("1~99 사이의 정수를 입력하시오>>");
		int num = scanner.nextInt();
		int total = 0;
		
        
		if ((num / 10) % 3 == 0)
			total ++;
		
        
		if ((num % 10) % 3 == 0)
			total ++;
		
		
		if (total == 1)
			System.out.println("박수짝");
            
		else if (total == 2)
			System.out.println("박수짝짝");	
		
        
		scanner.close();
	}
}

7. 2차원 평면에서 직사각형은 왼쪽 상단 모서리와 오른쪽 하단 모서리의 두 점으로 표현한다.

7. (100, 100)과 (200, 200)의 두 점으로 이루어진 사각형이 있을 때,

7. Scanner를 이용하여 정수 x와 y 값을 입력받고 점 (x, y)가 이 직사각형 안에 있는지를 판별하는 프로그램을 작성하라.

 

import java.util.Scanner;

public class PointInRectangle {

	public static void main(String[] args) {
    
		Scanner scanner = new Scanner(System.in);
		
        
		System.out.print("점 (x,y)의 좌표를 입력하시오>>");
		int x = scanner.nextInt();
		int y = scanner.nextInt();
		
        
		if (x >= 100 && x <= 200 && y >= 100 && y <= 200)	
			System.out.println("(" + x + "," + y + ")는 사각형 안에 있습니다.");
		
        
		sc.close();
	}
}

8. 2차원 평면에서 직사각형은 문제 7번처럼 두 점으로 표현된다.

8. 키보드로부터 직사각형을 구성하는 두 점 (x1, y1), (x2, y2)를 입력받아

8. (100, 100), (200, 200)의 두 점으로 이루어진 직사각형과 충돌하는지 판별하는 프로그램을 작성하라.

 

import java.util.Scanner;

public class CollisionWithRectangle {
	
	public static boolean inRect(int x, int y, int rectx1, int recty1, int rectx2, int recty2) {
    
		if ((x >= rectx1 && x <= rectx2) && (y >= recty1 && y <= recty2))
			return true;
		else
			return false;
	}
	
	
	
	public static void main(String[] args) {
		
		Scanner scanner = new Scanner(System.in);
		
        
		System.out.print("점 (x1,y1)의 좌표를 입력하시오>>");		
		int x1 = scanner.nextInt();
		int y1 = scanner.nextInt();
        
		System.out.print("점 (x2,y2)의 좌표를 입력하시오>>");		
		int x2 = scanner.nextInt();
		int y2 = scanner.nextInt();
		
        
		if (inRect(x1, y1, 100, 100, 200, 200)) { // 한 점이 주어진 직사각형 내부에 있는 경우
			if (inRect(x2, y2, 100, 100, 200, 200)) // 다른 한 점도 주어진 직사각형 내부에 있는 경우
				System.out.println("충돌하지 않습니다.");
			else // 다른 한 점이 주어진 직사각형 외부에 있는 경우
				System.out.println("충돌합니다.");
		}
		else  { // 한 점이 주어진 직사각형 외부에 있는 경우
			if (inRect(x2, y2, 100, 100, 200, 200)) // 다른 한 점이 주어진 직사각형 내부에 있는 경우
				System.out.println("충돌합니다.");
			else // 다른 한 점도 주어진 직사각형 외부에 있는 경우
				System.out.println("충돌하지 않습니다.");
		}
        
		
		scanner.close();
	}
}


9. 원의 중심을 나타내는 한 점과 반지름을 실수 값으로 입력받아라.

9. 그리고 실수 값으로 다른 점 (x, y)를 입력받아 이 점이 원의 내부에 있는지 판별하여 출력하라.

 

import java.util.Scanner;

public class PointInCircle {	

	public static void main(String[] args) {
    
		Scanner scanner = new Scanner(System.in);
		
        
		System.out.print("원의 중심과 반지름 입력>>");		
		double o1 = scanner.nextDouble();
		double o2 = scanner.nextDouble();
		double radius = scanner.nextDouble();
		
        
		System.out.print("점 입력>>");		
		double x = scanner.nextDouble();
		double y = scanner.nextDouble();		
		
        
		double distance = Math.sqrt(Math.pow(x - o1, 2) + Math.pow(y - o2, 2));
		
        
		if (distance <= radius)
			System.out.println("점 (" + x + ", " + y + ")는 원 안에 있다.");
		
        
		scanner.close();
	}
}

10. 원의 정보를 받기 위해 키보드로부터 원의 중심을 나타내는 한 점과 반지름을 입력받는다.

10. 두 개의 원을 입력받고 두 원이 서로 겹치는지 판단하여 출력하라.

 

import java.util.Scanner;

public class TwoCircleOverlap {	

	public static void main(String[] args) {
    
		Scanner scanner = new Scanner(System.in);
		
        
		System.out.print("첫번째 원의 중심과 반지름 입력>>");		
		double x1 = scanner.nextDouble();
		double y1 = scanner.nextDouble();
		double r1 = scanner.nextDouble();
		
        
		System.out.print("두번째 원의 중심과 반지름 입력>>");			
		double x2 = scanner.nextDouble();
		double y2 = scanner.nextDouble();
		double r2 = scanner.nextDouble();
		
        
		double distance = Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2));
		
        
		if (distance < r1 + r2)
			System.out.println("두 원은 서로 겹친다.");
		
        
		scanner.close();
	}
}

11. 숫자를 입력받아 3~5는 "봄", 6~8은 "여름", 9~11은 "가을", 12, 0, 1의 경우 "겨울"을,

11. 그 외 숫자를 입력한 경우 "잘못입력"을 출력하는 프로그램을 작성하라.

 

 

     (1) if-else 문을 이용하여 프로그램을 작성하라.

 

import java.util.Scanner;

public class Season {	

	public static void main(String[] args) {
    
		Scanner scanner = new Scanner(System.in);
		
        
		System.out.print("달을 입력하세요(1~12)>>");		
		int month = scanner.nextInt();


		if (month >= 3 && month <= 5)
			System.out.println("봄");
		else if (month >= 6 && month <= 8)
			System.out.println("여름");
		else if (month >= 9 && month <= 11)
			System.out.println("가을");
		else
			System.out.println("겨울");
		
        
		scanner.close();
	}
}

     

 

     (2) switch 문을 이용하여 프로그램을 작성하라.

 

import java.util.Scanner;

public class Season {	

	public static void main(String[] args) {
    
		Scanner scanner = new Scanner(System.in);
		
        
		System.out.print("달을 입력하세요(1~12)>>");		
		int month = scanner.nextInt();


		switch(month) {
			case 3:
			case 4:
			case 5:
				System.out.println("봄");
				break;
			case 6:
			case 7:
			case 8:
				System.out.println("여름");
				break;
			case 9:
			case 10:
			case 11:
				System.out.println("가을");
				break;
			case 12:
			case 1:
			case 2:
				System.out.println("겨울");
				break;
		}
		
        
		scanner.close();
	}
}

12. 사칙 연산을 입력받아 계산하는 프로그램을 작성하고자 한다.

12. 연산자는 +, -, *, /의 네 가지로 하고 피연산자는 모두 실수로 한다.

12. 피연산자와 연산자는 실행 사례와 같이 빈 칸으로 분리하여 입력한다.

12. 0으로 나누기 시 "0으로 나눌 수 없습니다."를 출력하고 종료한다.

 

 

       (1) 연산 식을 구분할 때 if-else 문을 이용하여 프로그램을 작성하라.

 

import java.util.Scanner;

public class Calculation {	

	public static void main(String[] args) {
    
		Scanner scanner = new Scanner(System.in);
		
        
		System.out.print("연산>>");		
		int x = scanner.nextInt();
		char op = scanner.next().charAt(0);
		int y = scanner.nextInt();


		if (op == '+')
			System.out.println(x + "+" + y + "의 계산 결과는 " + (x + y));
		else if (op == '-')
			System.out.println(x + "-" + y + "의 계산 결과는 " + (x - y));
		else if (op == '*')
			System.out.println(x + "*" + y + "의 계산 결과는 " + (x * y));
		else if (op == '/')
			System.out.println(x + "/" + y + "의 계산 결과는 " + (x / y));
		
        
		scanner.close();
	}
}
import java.util.Scanner;

public class Calculation {	

	public static void main(String[] args) {
    
		Scanner scanner = new Scanner(System.in);
		
        
		System.out.print("연산>>");		
		int x = scanner.nextInt();
		String op = scanner.next();
		int y = scanner.nextInt();


		if (op.equals("+"))
			System.out.println(x + "+" + y + "의 계산 결과는 " + (x + y));
		else if (op.equals("-"))
			System.out.println(x + "-" + y + "의 계산 결과는 " + (x - y));
		else if (op.equals("*"))
			System.out.println(x + "*" + y + "의 계산 결과는 " + (x * y));
		else if (op.equals("/"))
			System.out.println(x + "/" + y + "의 계산 결과는 " + (x / y));
		
        
		scanner.close();
	}
}

 

 

       (2) 연산 식을 구분할 때 switch 문을 이용하여 프로그램을 작성하라.

 

import java.util.Scanner;

public class Calculation {	

	public static void main(String[] args) {
    
		Scanner scanner = new Scanner(System.in);
		
        
		System.out.print("연산>>");		
		int x = scanner.nextInt();
		char op = scanner.next().charAt(0);
		int y = scanner.nextInt();


		switch(op) {
			case '+':
				System.out.println(x + "+" + y + "의 계산 결과는 " + (x + y));
				break;
			case '-':
				System.out.println(x + "-" + y + "의 계산 결과는 " + (x - y));
				break;
			case '*':
				System.out.println(x + "*" + y + "의 계산 결과는 " + (x * y));
				break;
			case '/':
				System.out.println(x + "/" + y + "의 계산 결과는 " + (x / y));
				break;
		}


		scanner.close();
	}
}