Java - adding value in a while loop

后端 未结 4 1227
栀梦
栀梦 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 14:57

    Declare the int sum variable outside of the while loop and only have one guess = keyboard.nextInt() inside the loop. Add the user's guess to the sum in the loop as well.

    Then after the loop output the user's sum.

    I.e.:

    int sum;
    while(guess != 0)
    {   
        guess = keyboard.nextInt();
        sum += guess;
    }
    System.out.println("Total: " + sum");
    

    Edit: also remove the guess2 variable, as you will no longer need it.

    0 讨论(0)
  • 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!

    0 讨论(0)
  • 2021-01-27 15:04

    The code will be as below :

     public static void main(String[] args) throws Exception {
         Scanner keyboard = new Scanner(System.in);
         int input = 0;
         int total = 0;
         System.out.println("Start entering the number");
         while((input=keyboard.nextInt()) != 0)
             {   
                 total = input + total;
             }
        System.out.println("The program exist because 0 is entered and sum is "+total);
    }
    
    0 讨论(0)
  • 2021-01-27 15:12

    Programming by Doing :)

        int x = 0;
        int sum = 0;
        System.out.println("I will add up the numbers you give me.");
        System.out.print("Number: ");
        x = keyboard.nextInt();
        while (x != 0) {
            sum = x + sum;
            System.out.println("The total so far is " + sum + ".");
            System.out.print("Number: ");
            x = keyboard.nextInt();
        }
        System.out.println("\nThe total is " + sum + ".");
    
    0 讨论(0)
提交回复
热议问题