How to sum any amount of user inputted numbers from a single line

后端 未结 1 460
感动是毒
感动是毒 2020-12-22 11:53

Trying to figure out how I would take any amount of inputted numbers from a user and add them together

Example user input: 1 2 3 4 Sum = 10

The user can put

相关标签:
1条回答
  • 2020-12-22 12:05

    It is very easy actually

    import java.util.Scanner;
    
    public class JavaApplication115 {
    
        public static void main(String[] args) {
            System.out.println("write numbers, if you write zero, program ends");
            Scanner input = new Scanner(System.in); //just copy-and paste this line, you dont have to understand it yet.
            int number;
            int sum = 0;
            do {
                number = input.nextInt(); //this reads number from input and store its value in variable number
                sum+= number; //here you add number to the total sum
            } while(number != 0); //just repeat cycle as long as number is not zero
    
            System.out.println("Sum is : " + sum);
        }
    
    }
    

    Working code based on your code :

    public static void main(String[] args) {
        Scanner kb = new Scanner(System.in);
        int score = 0;
        int sum = 0;
    
        System.out.println("Enter numbers here");
        String line = kb.nextLine();
    
        kb = new Scanner(line); //has to do this to make the kb.hasNexInt() work.
        while (kb.hasNextInt()) {
            score = kb.nextInt();
            sum += score;
        }
        System.out.println(sum);
    }
    

    Also if you are interested in "minimal" version, which is the same as the one before, but using as less code as possible, here it is :

    public static void main(String[] args) {
        int sum = 0;
        System.out.println("Enter numbers here");
        Scanner kb = new Scanner((new Scanner(System.in)).nextLine()); //has to do this to make the kb.hasNexInt() work.
        while (kb.hasNextInt()) {
            sum += kb.nextInt();
        }
        System.out.println(sum);
    }
    

    Find sum of each line as long as sum is not zero (based on second block of code) :

    public static void main(String[] args) {
        System.out.println("Enter numbers here");
        int sum;
        do {
            Scanner kb = new Scanner(System.in);
            int score = 0;
            sum = 0;
            String line = kb.nextLine();
            kb = new Scanner(line); //has to do this to make the kb.hasNexInt() work.
            while (kb.hasNextInt()) {
                score = kb.nextInt();
                sum += score;
            }
            System.out.println("Sum = " + sum);
        } while (sum != 0);
    }
    
    0 讨论(0)
提交回复
热议问题