Java - 在while循环中添加值

时间:2014-02-13 20:33:31

标签: java

这只是伤害了我的大脑。 http://programmingbydoing.com/a/adding-values-in-a-loop.html

  

编写一个程序,从用户那里获得几个整数。总结他们给你的所有整数。当他们输入0时停止循环。显示最后的总数。

到目前为止我得到了什么:

Scanner keyboard = new Scanner(System.in);
    System.out.println("i will add");
    System.out.print("number: ");
    int guess = keyboard.nextInt();
    System.out.print("number: ");
    int guess2 = keyboard.nextInt();




    while(guess != 0 && guess2 != 0)
    {   

        int sum = guess + guess2;
        System.out.println("the total so far is " + sum);
        System.out.print("number: ");
        guess = keyboard.nextInt();
        System.out.print("number: ");
        guess2 = keyboard.nextInt();
        System.out.println("the total so far is " + sum);

    }
    //System.out.println("the total so far is " + (guess + guess2));
}   

4 个答案:

答案 0 :(得分:0)

在while循环之外声明int sum变量,循环内只有一个guess = keyboard.nextInt()。将用户的猜测添加到循环中的总和。

然后在循环后输出用户的总和。

即:

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

修改也会移除guess2变量,因为您将不再需要它。

答案 1 :(得分:0)

代码如下:

 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);
}

答案 2 :(得分:0)

通过执行编程:)

    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 + ".");

答案 3 :(得分:0)

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 + ".");
    }
}

首先提示用户输入数字。然后将该数字存储为总数(总数+ =数字或总数=总数+数字)。然后,如果输入的数字不是0,则执行while循环。每次用户输入非零数字时,该数字总共存储(总数值越来越大),而while循环则要求另一个数字。如果用户输入0,则while循环中断,程序显示total total中的值。 :D我自己是一个初学者,在弄清楚之前对逻辑有一点问题。快乐的编码!