0

我正在通过Learn Java The Hard Way,我被困在这个学习练习中,即使用一个while循环来做与这段代码相同的事情。我想知道你们是否可以帮助我。我的大多数尝试都导致了无限的 while 循环,这是我不想要的。

import java.util.Scanner; 

public class RunningTotal
{   
    public static void main( String[] args)
    {
        Scanner input = new Scanner(System.in);

        int current, total = 0;

        System.out.print("Type in a bunch of values and I'll ad them up. ");
        System.out.println( "I'll stop when you type a zero." );

        do
        {   
            System.out.print(" Value: ");
            current = input.nextInt();
            int newtotal = current + total;
            total = newtotal; 
            System.out.println("The total so far is: " + total);
        }while (current != 0);

        System.out.println( "Final total: " + total);

    }
}
4

4 回答 4

3

一个不会改变那么多代码的解决方案:

int current = -1;

while (current != 0) {
    System.out.print(" Value: ");
    current = input.nextInt();
    int newtotal = current + total;
    total = newtotal; 
    System.out.println("The total so far is: " + total);
}
于 2013-08-17T00:00:55.183 回答
0

我不明白为什么当用户输入 0 时您要处理(添加到总数)。我知道这没有什么区别,但为什么要进行不必要的计算?

还有为什么要int newtotal在每个循环中定义。您可以简单地将总和添加到总数中。

所以while循环代码将如下所示

    while((current = input.nextInt()) != 0) {
       total = total + current;
        System.out.println("The total so far is: " + total);
    } 
于 2013-08-17T04:00:47.043 回答
-1

将我的评论变成答案:

一种可能的解决方案:

boolean flag = true;
while(flag)
{   
    System.out.print(" Value: ");
    current = input.nextInt();
    int newtotal = current + total;
    total = newtotal; 
    System.out.println("The total so far is: " + total);
    if(current == 0)
        flag = false;
}

另一种可能的解决方案:

while(true)
{
    System.out.print(" Value: ");
    current = input.nextInt();
    int newtotal = current + total;
    total = newtotal; 
    System.out.println("The total so far is: " + total);
    if(current == 0)
        break;
}
于 2013-08-16T23:50:21.577 回答
-1

接下来呢:

Scanner input = new Scanner(System.in);

System.out.print("Type in a bunch of values and I'll ad them up. ");
System.out.println( "I'll stop when you type a zero." );

int total = 0;
for (int current = -1; current != 0;) {
    System.out.print(" Value: ");
    current = input.nextInt();
    total += current; 
    System.out.println("The total so far is: " + total);
}

System.out.println( "Final total: " + total);
于 2013-08-16T23:54:55.597 回答