ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 자바기초개념 다시잡기 자바의정석 - 연습문제 4장
    자바 기초 2021. 7. 23. 20:49

    남궁성님의 자바의 정석

     

    1. Chaper 4 - 조건문/반복문

    1. int형 변수 x가 10보다 크고 20보다 작을 때 true인 조건식
    public class Ch_4 {
    	public static void main(String[] args) {
    		Scanner sc = new Scanner(System.in);
    		
    		int x = sc.nextInt();
    		if (x > 10 && x <20) {
    			System.out.println("True");
    		} else {
    			System.out.println("False");
    		}
    	}
    }
    15
    True
    21
    False
    
    
    2~5번은 1번과 동일한 로직 문제 
    6. int형 변수 year가 400으로 나눠떨어지거나 또는 4로 나눠떨어지고 100으로 나눠떨어지지 않을 때 true인 조건식
    public class Ch_4 {
    	public static void main(String[] args) {
    		Scanner sc = new Scanner(System.in);
    		
    		int year = sc.nextInt();
    		
    		if (year % 400 == 0 || year % 4 == 0 && year % 100 != 0) {
    			System.out.println("True");
    		} else {
    			System.out.println("False");
    		}
    	}
    }
    151
    False
    400
    True
    
    
    7. boolean형 변수 powerOn가 false일 때 true인 조건식
    public class Ch_4 {
    	public static void main(String[] args) {
    		boolean powerOn = false;
    		if(!powerOn) {
    			System.out.println("True");
    		} else {
    			System.out.println("False");
    		}
    	}
    }
    True
    
    
    public static void main(String[] args) {
    		Scanner sc = new Scanner(System.in);
    		String str = sc.next();
    		
    		if (str.equals("yes")) {
    			System.out.println("True");
    		} else {
    			System.out.println("False");
    		}
    	}
    }
    asa
    False
    - 1부터 20까지의 정수 중에서 2 또는 3의 배수가 아닌 수의 총합을 구하시오
    // 2 또는 3의 배수가 아닌 것, 또는이 나와도 둘다 아이어야하기때문에 And
    public class Ch_4 {
    	public static void main(String[] args) {
    		int sum = 0;
    		for (int i=1; i<=20; i++) {
    			if(i % 2 != 0 && i % 3 != 0) { //
    				sum += i;
    			}
    		}
            System.out.println(sum);
    	}
    }
    73
    
    
    - 1+(1+2)+(1+2+3)+(1+2+3+4)+...+(1+2+3+...+10)의 결과를 계산하시오.
    // 중요포인트는 1 고정에 +()로 들어오는수가 sum에 1~10까지 변화하면서 들어오면 된다
    public class Ch_4 {
    	public static void main(String[] args) {
    		int sum = 0;
    		int totalsum = 0;
    		for (int i=1; i<=10; i++) {
    			sum += i; // 1~10 까지 합
    			totalsum += sum;
    		}
    		System.out.println(totalsum);
    	}
    }
    220
    
    
    - 1+(-2)+3+(-4)+... 과 같은 식으로 계속 더해나갔을 때, 몇까지 더해야 총합이 100이상이 되는지 구하시오.
    public class Ch_4 {
    	public static void main(String[] args) {
    		int sum = 0; // 총합 저장
    		int s = 1; //증감수와 연산할 변수
    		int num = 0; // 증감수 + s 연산을 담을 수 
    		
    		for (int i=1; true; i++, s=-s) { // 매반복마다 1, -1....
    			num = s * i; // 1 * 1, 2*-1 , 3 * 1
    			sum += num;
    			if (sum >= 100) {
    				break;
    			}
    			System.out.println("num="+num);
    			System.out.println("sum="+sum);
    		}
    	}
    }
    num=1
    sum=1
    num=-2
    sum=-1
    num=3
    sum=2
    num=-4
    sum=-2
    num=5
    sum=3
    num=-6
    sum=-3
    num=7
    sum=4
    .....
    num=199
    sum=100
    
    
    - 다음의 for문을 while문으로 변경하시오.
    
    public class Exercise4_5 {
    	public static void main(String[] args) {
    		for(int i=0; i<=10; i++) {
    			for(int j=0; j<=i; j++)
    				System.out.print("*");
    					System.out.println();
    		}
    	} // end of main
    } // end of class
    
    -->
    public class Ch_4 {
    	public static void main(String[] args) {
    		int i = 0;
    		while (i<=10) {
    			int j = 0;
    			while (j<=i) {
    				System.out.print("*");
    				j++;
    			}
    			System.out.println();
    			i++;
    		}
    	}
    }
    
    *while문을 써서 주사위 합 6 을 뽑기
    public class Ch_4 {
    	public static void main(String[] args) {
    		
    		int sum = 0;
    		while (true) {
    			int a = (int)(Math.random() * 6);
    			int b = (int)(Math.random() * 6);
    			System.out.println("(" + a + " , " + b + ")");
    			sum = a + b;
    			if (sum == 6) {
    				System.out.println("주사위 합이 " + sum + "이므로 프로그램이 종료 됩니다.");
    				System.exit(0);
    			}
    		}
    	}
    }
    
    
    -두 개의 주사위를 던졌을 때, 눈의 합이 6이 되는 모든 경우의 수를 출력하는 프로그램을 작성하시오.
    public class Ch_4 {
    	public static void main(String[] args) {
    		
    		for (int i=1; i<=6; i++) {
    			for (int j=1; j<=6; j++) {
    				if (i+j ==  6) {
    					System.out.println(i + " + " + j + " = " + (i+j));
    				}
    			}
    		}
    	}
    }
    1 + 5 = 6
    2 + 4 = 6
    3 + 3 = 6
    4 + 2 = 6
    5 + 1 = 6
    
    
    
    - 방정식 2x+4y=10의 모든 해를 구하시오. 단, x와 y는 정수이고 각각의 범위는 0<=x<=10, 0<=y<=10 이다.
    public class Ch_4 {
    	public static void main(String[] args) {
    		int a = 2;
    		int b = 4;
    		for (int x=0; x<=10; x++) {
    			for (int y=0; y<=10; y++) {
    				if (a*x + b*y == 10) {
    					System.out.println("x=" + x + " , " + "y=" + y);
    				}
    			}
    		}
    	}
    }
    x=1 , y=2
    x=3 , y=1
    x=5 , y=0
    
    - 숫자로 이루어진 문자열 str이 있을 때, 각 자리의 합을 더한 결과를 출력하는 코드를 완성하라. 만일 문자열이 "12345"라면, ‘1+2+3+4+5’의 결과인 15를 출력이 출력되어야 한다. (1)에 알맞은 코드를 넣으시오.
    class Exercise4_9 {
    	public static void main(String[] args) {
    		String str = "12345";
    		int sum = 0;
    		for(int i=0; i < str.length(); i++) {
    			/*
    			(1) 알맞은 코드를 넣어 완성하시오.
    			*/
    		}
    	System.out.println("sum="+sum);
    	}
    }
    -->
    public class Ch_4 {
    	public static void main(String[] args) {
    		String str = "12345";
    		int sum = 0;
    		for (int i=0; i<str.length(); i++) {
    			sum += str.charAt(i) - '0';
    			// char의 '1'에서 int형 1로 바꾸면 아스키코드값인 49가 나오는데
    			// 여기 49에서 1을 만들려면 48을 가지고 있는 아스키코드값인 '0'을 빼줘야함
    		}
    		System.out.println("sum="+sum);
    	}
    }
    sum=15
    
    
    - int타입의 변수 num 이 있을 때, 각 자리의 합을 더한 결과를 출력하는 코드를 완성하라. 만일 변수 num의 값이 12345라면, ‘1+2+3+4+5’의 결과인 15를 출력하라. (1) 에 알맞은 코드를 넣으시오
    class Exercise4_10 {
    	public static void main(String[] args) {
    		int num = 12345;
    		int sum = 0;
    		/*
    		(1) 알맞은 코드를 넣어 완성하시오.
    		*/
    		System.out.println("sum="+sum);
    	}
    }
    -->
    public class Ch_4 {
    	public static void main(String[] args) {
    		int num = 12345;
    		int sum = 0;
    		String temp = Integer.toString(num);
    		int[] digits = new int[temp.length()];
    		
    		for (int i=0; i<digits.length; i++) {
    			digits[i] = temp.charAt(i) - '0';
    			sum += digits[i];
    		}
    		System.out.println(sum);
    	}
    }
    or
    public class Ch_4 {
    	public static void main(String[] args) {
    		int num = 12345;
    		int sum = 0;
    		
    		while(num > 0) {
    			sum += num % 10; // 5 4 3 2 1 로 떨어짐
    			System.out.println(sum);
    			num /= 10;
    //			System.out.println(num);
    		}
    		System.out.println("sum=" + sum);
    	}
    }
    
    
    - 1과 1부터 시작하는 피보나치수열의 10번째 수는 무엇인지 계산하는 프로그램을 완성하시오.
    public class Ch_4 {
    	public static void main(String[] args) {
    		int a = 0;
    		int b = 1;
    		int c = 0;
    		
    		for (int i=1; i<10; i++) {
    			c = a+b;//1, 2, 3,
    			a = b;//1, 1, 2
    			b = c;//1, 2, 3
    			System.out.println("c="+c);
    		}
    	}
    }
    55
    
    
    - 구구단 일부분만 출력
    public class Ch_4 {
    	public static void main(String[] args) {
    		for (int i=2; i<10; i++) {
    			for (int j=1; j<10; j++) {
    				System.out.println(i + " * " + j + " = " + i*j);
    				if (j >= 3) {
    					break;
    				}
    			}
    		}
    	}
    }
    2*2=4 3*2=6 4*2=8
    2*3=6 3*3=9 4*3=12
    
    
    - 다음은 주어진 문자열(value)이 숫자인지를 판별하는 프로그램이다. (1)에 알맞은 코드를 넣어서 프로그램을 완성하시오.
    public class Ch_4 {
    	public static void main(String[] args) {
    		String value ="12o34";
    		char ch = ' ';
    		boolean isNumber = true;
    		// 반복문과 charAt(int i)를 이용해서 문자열의 문자를
    		// 하나씩 읽어서 검사한다.
    		for (int i = 0; i < value.length(); i++) {
    			ch = value.charAt(i);
    			if (!('0' <= ch && ch <= '9')) { //ch가 숫자가 아니면 밑으로가서 isNumber false
    				isNumber = false; //즉 'o'에서 걸림
    				break;
    			}
    		}
    		if (isNumber) {
    			System.out.println(value + "는 숫자입니다.");
    		} else {
    			System.out.println(value + "는 숫자가 아닙니다.");
    		}
    	} // end of main
    } // end of class
    
    
    - 숫자맞추기
    public class Ch_4 {
    	public static void main(String[] args) {
    		
    		int answer = (int)(Math.random() * 100);
    		int input = 0;
    		int count = 0;
    		
    		Scanner sc = new Scanner(System.in);
    		do {
    			count++;
    			System.out.println("1~100사이의 숫자를 맞춰보세요.>");
    			input = sc.nextInt();
    			
    			if (answer > input) {
    				System.out.println("Up!");
    			} else if (answer < input) {
    				System.out.println("Down!");
    			} else {
    				System.out.println("정답! 정답은 " +answer+"입니다");
    				System.out.println(count+"번 만에 맞췄네요!");
    				break;
    			}
    		} while(true);
    	}
    }
    Down!
    1~100사이의 숫자를 맞춰보세요.>
    93
    Down!
    1~100사이의 숫자를 맞춰보세요.>
    92
    정답! 정답은 92입니다
    8번 만에 맞췄네요!
    
    
    - 펠린드롬!
    public class Ch_4 {
    	public static void main(String[] args) {
    		
    		int number = 12321;
    		int tmp = number;
    		
    		int result = 0;
    		
    		while (tmp != 0) {
    			result = result * 10 + tmp % 10;
    			tmp /= 10;
    		}
    		
    		if (number == result) {
    			System.out.println(number+"는 회문수네요");
    		} else {
    			System.out.println(number+"는 회문수가 아니네요");
    		}
    	}
    }
    12321는 회문수네요
Designed by Tistory.