728x90
문제
x, y값 입력받고 x의 y승 구하기
무한 반복하게 만들기
package loop;

import java.util.Scanner;

public class ForTest05 {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int x, y;

		while (true) {
			int mul = 1; // 이게 반복문 안에 있어야지 끝날때마다 초기화가 가능.
			System.out.println("거듭제곱을 구하세요");
			System.out.println("x의 y승을 계산하시오");

			System.out.print("x값 입력 : ");
			x = sc.nextInt();
			System.out.print("y값 입력 : ");
			y = sc.nextInt();

			for (int i = 1; i <= y; i++) {
				mul *= x;
			}
			System.out.println(x + "의 " + y + "승 " + mul);
			System.out.println();
		}

	}
}

System.in.read() 사용하는 방법
read는 숫자가 아닌 문자로 읽기 때문에 
숫자로 입력을 해도 아스키코드로 인식을 한다. 그래서 입력값에 -48을 해줘야지 사용자가 원하는 값을 입력할 수 있다.

package loop;

import java.io.IOException;

//System.in.read(); 사용한 방법
public class ForTest05_2 {
	public static void main(String[] args) throws IOException {

		while (true) {
			System.out.print("x값 입력 : ");
			int x = System.in.read() - 48;// 숫자가 아닌 문자로 읽기 때문에 0의 아스키값을 빼줘야함
			System.in.read(); // 엔터값까지 입력하기 때문에 buffer에 입력값을 지우기 위해 추가
			System.in.read();

			System.out.print("y의 값 입력 : ");
			int y = System.in.read() - '0';
			System.in.read();
			System.in.read();

			int mul = 1;
			for (int i = 1; i <= y; i++) {
				mul *= x;
			}
			System.out.println(x + "의 " + y + " 승은 " + mul);
			System.out.println();
		}
	}

}
728x90

'JAVA' 카테고리의 다른 글

배열 연습문제04  (0) 2020.09.12
배열, 2차원 배열 정리  (0) 2020.09.12
숙제-더하기 연습 프로그램(for, 중첩for, while, bufferedReader,  (0) 2020.09.09
숙제-NumberGame(bufferedReader, while, if )  (0) 2020.09.09
switch 연습02  (0) 2020.09.08

+ Recent posts