gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 14:13:55 25 4
gpt4 key购买 nike

我正在学习 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);

}
}

最佳答案

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

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

关于java - 如何在此代码中使用 while 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18283594/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com