【发布时间】:2018-06-20 16:47:12
【问题描述】:
这是我的 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的返回值,它应该简单地说再见!
【问题讨论】:
-
如果值为负数,您需要在之前打破循环。
-
但我不能跳出循环。如果我在循环结束时中断,则不会输入下一个整数。
标签: java loops while-loop extra