JAVA 문제풀이

반복문 실습문제.5

Rocomi 2024. 6. 19. 10:02

사용자로부터 두 개의 값을 입력 받아 그 사이의 숫자를 모두 출력하세요.

만일 1 미만의 숫자가 입력됐다면 “1 이상의 숫자를 입력해주세요“를 출력하세요.

ex.

첫 번째 숫자 : 8

두 번째 숫자 : 4

4 5 6 7 8

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package com.kh.practice.chap02.loop;
 
import java.util.Scanner;
 
public class LoopPractice {
 
    public void practice6() {
        Scanner sc = new Scanner(System.in);
 
        System.out.print("첫 번째 숫자 : ");
 
        int num1 = sc.nextInt();
 
        System.out.print("두 번째 숫자 : ");
 
        int num2 = sc.nextInt();
 
        if (num1 < 1 || num2 < 1) {
 
            System.out.println("1이상의 숫자를 입력해주세요.");
 
        } else {
            if (num1 >= num2) {
 
                for (int i = num2; i <= num1; i++) {
 
                    System.out.print(i);
 
                    if (i != num1) {
                        System.out.print(" ");
                    }
 
                }
            } else {
                for (int i = num1; i <= num2; i++) {
 
                    System.out.print(i);
 
                    if (i != num2) {
                        System.out.print(" ");
                    }
 
                }
 
            }
        }
    }
    
}
cs