这是我的while循环。程序对整数求和,直到输入负数。此时,循环应该中断,它应该打印"再见"。但是,它每次在说再见之前都会添加负数。我不确定这里出了什么问题。请帮忙?!
import java.util.Scanner;
public class While {
public static void main(String[] args)
{
int input = 5;
int sum = 0;
while(input >= 0)
{
System.out.println("Please enter a positive integer: ");
Scanner in = new Scanner (System.in);
input = in.nextInt();
sum = sum + input;
System.out.println("Running total: " + sum );
}
System.out.println("Goodbye!" );
}
测试:
Please enter a positive integer:
5
Running total: 5
Please enter a positive integer:
10
Running total: 15
Please enter a positive integer:
-1
Running total: 14
Goodbye!
我不想得到 14 的返回值,它应该简单地说再见!
您需要使用 break 关键字。您的循环将始终完成,因此只有在您添加负数后才会对 while 进行检查。您可以更改为以下内容:
while(true)
{
System.out.println("Please enter a positive integer: ");
Scanner in = new Scanner (System.in);
input = in.nextInt();
if(input <0){
break;
}
sum = sum + input;
System.out.println("Running total: " + sum );
}
或者这个:
while(input >= 0)
{
System.out.println("Please enter a positive integer: ");
Scanner in = new Scanner (System.in);
input = in.nextInt();
if(input <0){
break;
sum = sum + input;
System.out.println("Running total: " + sum );
}
}
或者如果需要,完全避免 if 语句(尽管这不是循环的重点(:
while(input >= 0)
{
sum = sum + input;
System.out.println("Please enter a positive integer: ");
Scanner in = new Scanner (System.in);
input = in.nextInt();
System.out.println("Running total: " + sum );
}
这是我的解决方案:
while(input >= 0)
{
sum = sum + input;
System.out.println("Running total: " + sum );
System.out.println("Please enter a positive integer: ");
Scanner in = new Scanner (System.in);
input = in.nextInt();
}
System.out.println("Goodbye!" );
}
通过在初始化时和输入第一个整数之前计算总和。它似乎按照我现在想要的方式工作。感谢您的帮助。