반응형

1. 입력한 두 정수 사이의 정수의 합

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
import java.util.Scanner;
 
public class Exam2_01 {
    
    public static void main(String[] args) {
        int sum = 0, n1, n2, n;
        Scanner input = new Scanner(System.in);
 
        System.out.println("input n1, n2, " + "add n1 from n2.");
        System.out.print("n1: ");
        n1 = input.nextInt();
        System.out.print("n2: ");
        n2 = input.nextInt();
 
        // n2가 n1보다 작은 경우
        if (n1 > n2) {
            n = n2;
            n2 = n1;
            n1 = n;
        }
 
        for (n = n1; n <= n2; n++) {
            sum = sum + n;
        }
 
        System.out.println(n1 + " 부터 " + n2 + " 까지의 정수의 합은 " + sum + " 이다");
        System.out.println("sum of integers from " + n1 + " to " + n2 + " is " + sum);
 
        input.close();
    }
}
cs



2. 입력한 두 정수 사이의 정수의 합 (try, catch)

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
import java.util.InputMismatchException;
import java.util.Scanner;
 
// input two integers n1, n2, and add the integers between n1 and n2.
public class Exam2_02 {
 
    public static void main(String[] args) {
        
        int sum = 0, n1, n2, n;
        Scanner input = new Scanner(System.in);        
        boolean flag = true;
        
        while (flag) {            
            try {
                System.out.println("input n1, n2, then add from n1 to n2.");
                System.out.print("a: ");
                n1 = input.nextInt();
                System.out.print("b: ");
                n2 = input.nextInt();
                flag = false;
            } catch (InputMismatchException ime) {
                System.out.println("Exception: " + ime);
                input.next();
                continue;
            }
            
            for (n = n1; n <= n2; n++) { sum += n; }            
            System.out.println("sum of integers from " + n1 + " to " + n2 + " is " + sum);            
        }
        
        input.close();
        
    }
}
cs
반응형