O
O
O1dse1fm2020-11-17 10:07:31
Java
O1dse1fm, 2020-11-17 10:07:31

How to display the sum of numbers from the keyboard?

Task with Javarush: Let's write a program in which you need to enter numbers from the keyboard and calculate their sum until the user enters the word "ENTER".
Display the amount received on the screen and exit the program.
I don’t use any methods yet, and for me the solution is quite logical:

Scanner numbers = new Scanner(System.in);
        int sum = 0;
        int a = numbers.nextInt();
        
        boolean b = false;
        while(!b) {
            String c = numbers.nextLine();
            b = c.equals("ENTER");
            System.out.println(sum += a);
        }

but it does not pass the test, does not display the sum of numbers, I can’t understand why, I opened the author’s solution:

Scanner scanner = new Scanner(System.in);

        int sum = 0;
        boolean isExit = false;
        while (!isExit) {
            String line = scanner.nextLine();

            if (line.equals("ENTER")) {
                isExit = true;
            } else {
                int number = Integer.parseInt(line);
                sum += number;
            }
        }
        System.out.println(sum);


in principle, everything is clear, but it is more complex, a cycle within a cycle, I don’t see the point in this; int number = Integer.parseInt(line) - and I do not fully understand this line, the program will convert everything from the scanner object to int, I just created a new int, i.e. essentially the same thing, only in different ways, but the main question, sum += a - the counting scheme is the same, but it doesn’t work for me, what’s wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sand, 2020-11-17
@sand3001

Why is it
System.out.println(sum += a);
in the loop body, and why "a" and not "c"?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question