본문 바로가기
자료구조 | 알고리즘/공부

반복2. 양수만 입력하기

by 동기 2021. 11. 2.
반응형
양수만 입력하기

 

class SumForPos {
	public static void main(String[] args){
    	Scanner scan = new Scanner(System.in);
        int n;
        int sum = 0;
        
        System.out.println("1부터 n 까지의 합을 구합니다.");
        
        //n이 0보다 작으면 계속 반복
        do{
        	System.out.print("n의 값:");
            n = scan.nextInt
        }while(n<=0);
        
        for(int i = 1; i <= n; i++)sum += i;
        
        System.out.println("1부터"+n+"까지의 합은" + sum + "입니다.");
    }
}

n 의 값으로 0 이하의 값을 입력하면 "n의 값:" 이라고 출력되며 사용자에게 다시 입력하도록 요구한다. 즉 양수만 입력 받기 위해 작성해 놓은 것이다.

 

📌사전 판단 반복과 사후 판단 반복의 차이점

사전 판단 반복문인 while 문과 for문은 처음에 제어식을 평가한 결과가 0 이면 루프 본문은 한번도 실행되지 않는다. 이와 달리 사후 판단 반복문인 do while 문은 루프 본문이 반드시 한 번은 실행된다.

 

🦊Q10. 두 변수 a,b 에 정수를 입력하고 b-a 를 출력하는 프로그램을 작성하세요. 단 변수 b에 입력한 값이 a 이하면 변수 b의 값을 다시 입력하세요.

public class Application {

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		int a;
		int b;

		a = scan.nextInt();
		b = scan.nextInt();
		System.out.println("a의 값 : "+a);
		System.out.println("b의 값 : "+b);
		while(b>=a) {
			System.out.println("a보다 큰 값을 입력하세요");
			b = scan.nextInt();
			System.out.println("b의 값 : "+b);
		}
		System.out.println("b - a는 : "+(b-a)+ "입니다.");
	}

}

 

🦊Q11. 양의 정수를 입력하고 자릿수를 출력하는 프로그램을 작성하세요.
ex) 입력 : 135 / 출력 :  '그 수 자리는 3자리 입니다.'

입력 : 1314 / 출력 : '그 수 자리는 4자리 입니다.'

public class Application {

	public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        Long a = scan.nextLong();
        String strA = String.valueOf(a);
        int digit = strA.length();
        System.out.printf("그 수 자리는 %d 입니다",digit);
	}

}

반응형

'자료구조 | 알고리즘 > 공부' 카테고리의 다른 글

반복1. 1부터 n 까지의 정수 합 구하기  (0) 2021.10.06
기본 알고리즘  (0) 2021.10.06

댓글