Java - adding value in a while loop

后端 未结 4 1229
栀梦
栀梦 2021-01-27 14:46

this one just is hurting my brain. http://programmingbydoing.com/a/adding-values-in-a-loop.html

Write a program that gets several integers from the user.

4条回答
  •  花落未央
    2021-01-27 15:01

    import java.util.Scanner;
    
    public class AddingInLoop {
        public static void main(String[] args) {
            Scanner keyboard = new Scanner(System.in);
    
            int number, total = 0;
    
            System.out.print("Enter a number\n> ");
            number = keyboard.nextInt();
            total += number;
    
            while (number != 0) {
                System.out.print("Enter another number\n> ");
                number = keyboard.nextInt();
                total += number;
            }
            System.out.println("The total is " + total + ".");
        }
    }
    

    You first prompt the user to enter a number. Then you store that number into total (total += number OR total = total + number). Then, if the number entered wasn't 0, the while loop executes. Every time the user enters a nonzero number, that number is stored in total ( the value in total is getting bigger) and the while loops asks for another number. If and when a user enters 0, the while loop breaks and the program displays the value inside total. :D I myself am a beginner and had a bit of an issue with the logic before figuring it out. Happy coding!

提交回复
热议问题