2014-02-13 190 views
0

这只是伤害了我的大脑。 http://programmingbydoing.com/a/adding-values-in-a-loop.htmlJava - 在while循环中增加值

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

什么Ive得到了迄今:

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

这里有一个实际的问题吗? –

+0

逻辑错误.. – Kick

+1

提示:“停止循环,当它们进入0”不同于“停止循环时,他们输入两个0”。 – ajb

回答

0

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

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

即:

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

编辑:也去掉guess2变量,你将不再需要它。

+0

非常感谢你:) – tamalon

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

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

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

你先提示用户输入一个数字

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