我在Java中的情况;
我想问一下用户把一些数字和总共有这些数字。 但是,如果用户输入一个负数,将结束循环;
目前我有如下while循环;
double sum = 0;
double Input = 0;
System.out.println("Please enter the numbers (negative to end)")
System.out.println("Enter a number");
Scanner kdb = new Scanner(System.in);
Input = kdb.nextDouble();
while (Input > 0)
{
System.out.println("Enter an income");
Input = kdb.nextDouble();
sum = Input;
}
然而,它没有做的工作。 如果用户放在40,60,50,和-1正确的结果应为150; 我的循环导致109。
请帮忙!
非常感谢! 成龙
double sum = 0;
double Input = 0;
System.out.println("Please enter the numbers (negative to end)")
System.out.println("Enter a number");
Scanner kdb = new Scanner(System.in);
Input = kdb.nextDouble();
while (Input > 0)
{
sum += Input;
System.out.println("Enter an income");
Input = kdb.nextDouble();
}
我建议变量名不下手大写字母。
这应该工作!
double sum = 0;
double Input = 0;
boolean Adding= true;
System.out.println("Please enter the numbers (negative to end)");
Scanner kdb = new Scanner(System.in);
while(Adding == true)
{
System.out.print("Enter a number: ");
Input = kdb.nextDouble();
if(Input > 0)
{
sum+= Input;
}
else
Adding = false;
}
System.out.println("Your sum is: " + sum);
第一输入值是由第二个覆盖由于该总和在循环结束才进行。
**double sum = 0;
double Input = 0;
System.out.println("Please enter the numbers (negative to end)");
System.out.println("Enter a number");
Scanner kdb = new Scanner(System.in);
Input = kdb.nextDouble();
while (Input>0)
{
sum+= Input;
System.out.println("Enter an income");
Input = kdb.nextDouble();
}
System.out.println(sum);
}**
输出是:
Please enter the numbers (negative to end)
输入一个数字,40进入收入50进入收入60进入收入150.0 -1
文章来源: How to sum up the resultes in a while loop while centain input will end the while loop?