Felipe Felipe - 1 year ago 36
Java Question

How to break a program when the enter is empty

I have a function that, for example, read numbers line by line, and calculates the sum of those numbers.
The user enters the numbers, one number per line, and when enters 'null', the program breaks and give the result.
For example:





The result is 17

How can I do that the program breaks when the input is empty and give the result?


This is the code that I thought of using scanner. The comment in the code is where I think you might have messed up on, key areas, and things that you asked.

public static void sumInputs(){
    Scanner data=new Scanner(System.in);
    ArrayList <Double> allNumbers=new ArrayList<>();
            //IMPORTANT: Notice I use "nextLine" and not "next", because next will wait till user inputs something not null
            //and ignours the "enter" key pressed, while "nextLine" executes when the user presses the key "enter" regardless
            //of whether there is input.
            //I would imagine this is your problem
            String number=data.nextLine();

            //The part you are looking for
            //Right here is the part you are looking for
                //what to do if it is not null (store the numbers
                //in an ArrayList).
                //add up all the numbers if it is null
                double sum = 0;
                for( double i : allNumbers) {
                    sum += i;
                System.out.println("The result is "+ sum);
        }catch(InputMismatchException e){
            System.out.println("Not number");