java 加法运算

 

//find sum of two numbers

import java.util.Scanner;

public class Numbers {

    public static void main(String[] args) {
        int num1, num2, sum;
        Scanner ip = new Scanner(System.in);
        System.out.print("Enter num1: ");
        num1 = ip.nextInt();
        System.out.print("Enter num2: ");
        num2 = ip.nextInt();
        sum = num1 + num2;
        System.out.println("The sum of " + num1 + " and " + num2 + " is " + sum);
        ip.close();
    }

}



OUTPUT:
Enter num1: 35
Enter num2: 45
The sum of 35 and 45 is 80

 2

//find sum of n numbers

import java.util.Scanner;

public class Numbers {

    public static void main(String[] args) {
        int n, temp, sum = 0;
        Scanner ip = new Scanner(System.in);
        System.out.print("Enter the total number of input: ");
        n = ip.nextInt();
        for (int i = 1; i <= n; i++) {
            System.out.print("Enter input " + i + ": ");
            temp = ip.nextInt();
            sum = sum + temp;
        }
        System.out.println("The sum of all input numbers is: " + sum);
        ip.close();
    }

}



OUTPUT:
Enter the total number of input: 5
Enter input 1: 6
Enter input 2: 3
Enter input 3: 8
Enter input 4: 2
Enter input 5: 9
The sum of all input numbers is: 28

 

你可能感兴趣的:(java 加法运算)