2014-02-13 189 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); 
}