如何在此代码中使用while循环?

时间:2013-08-16 23:42:29

标签: java loops while-loop do-while

我正在通过Learn Java The Hard Way工作,我坚持这个研究练习,即使用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 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分:0)

我不明白为什么在用户输入0时你正在处理(加总)我知道它没有区别,但为什么不必要的计算呢?

另外,为什么在每个循环中定义int newtotal。您只需将总和添加到总数中即可。

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

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

答案 2 :(得分:-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;
}

答案 3 :(得分:-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);