繁体   English   中英

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

[英]How can I use a while loop in this code?

我正在通过“学习Java困难的方式”进行工作,并且坚持进行此学习练习,即使用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);

    }
}

不会更改太多代码的解决方案:

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

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

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

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

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

将我的评论变成答案:

一种可能的解决方案:

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

接下来呢:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM