我必须写一个do循环来读取整数并计算它们的总和。连续两次读取零或相同值时停止。例如,如果输入为1 2 3 4 4,则总和为14并且循环停止。如果用户输入为0,我也需要知道是否可以为do while语句使用多个参数,或者如果我需要在stamenent中嵌套另一个参数。
int input = 0;
int total = 0;
int update = 0;
System.out.println("Enter any number");
total = inputDevice.nextInt();
do
{
System.out.println("Enter any number");
input = inputDevice.nextInt();
// Do i have to nest a do-while statement here?
total = total + input;
}while((input != 0); // Or How would i insert a second parameter that stops the loop when a number is entered twice in a row?
For the above parameters I know i would do && to start the second parameter, I just cannot figure out the logic statement I would insert as the parameter.
System.out.println("The sum of the numbers is " + total);
}
}
答案 0 :(得分:3)
您需要将最后一个输入保存在变量中,然后将其与实际输入进行比较(如果它们相等,则break
while
循环。
试试这个:
int last_input = 0;
int input = 0;
int total = 0;
int update = 0;
Scanner inputDevice = new Scanner(System.in);
do
{
System.out.println("Enter any number");
input = inputDevice.nextInt();
total = total + input;
if(last_input == input)
break;
last_input = input;
}while(input != 0); // Or How would i insert a second parameter that stops the loop when a number is entered twice in a row?
System.out.println("The sum of the numbers is " + total);
答案 1 :(得分:2)
这很简单,您可以使用“普通”while
循环执行此操作,例如用
do-while
语句
while (true) {
System.out.println("Enter any number");
input = inputDevice.nextInt();
total = total + input;
if ((input == 0) || (input == update)) {
break; // Exit the loop
} else {
update = input; // Remember the last value
}
}
上面的示例重用了update
变量,该变量似乎没有用于任何其他变量。如果需要它用于其他目的,它当然可以用另一个变量替换,在input
的同一区域中声明。
答案 2 :(得分:1)
int prevInput = 0;
bool bFirstRun = true
do
{
System.out.println("Enter any number");
if(!bFirstRun)
{
prevInput = input
}
input = inputDevice.nextInt();
bFirstRun = false;
total = total + input;
if(prevInput == input)
break;
}while((input != 0);
我会在上面添加一个prevInput参数和一个布尔值来检查它是否是第一次通过循环。如果是,那么不检查先前的输入,如果它不是第一次通过那么检查输入到前一个(在它被添加到总数之后)并且如果它相同然后从循环中断。
答案 3 :(得分:0)
在这里......试试这个。它更简单
int num1 = 0, num2 = 0, total = 0;
do {
num2 = num1;
System.out.println("Enter any number");
num1 = inputDevice.nextInt();
total += num1;
System.out.println("The sum of the numbers is " + total);
} while (num1 != num2 && num1 != 0);