感谢您查看我的代码。 我正在学习 java,遇到了一个让我抓狂的问题。
/*
* The loop reads positive integers from standard input and that
* terminates when it reads an integer that is not positive. After the loop
* terminates, it prints out, separated by a space and on a single line, the
* sum of all the even integers read and the sum of all the odd integers
*/
问题是变量没有相加!我知道我的语法很好。我认为关于 java 语言,我不理解循环的工作原理和添加方式。
import java.util.Scanner;
class Testing2 {
public static void main(String[] args) {
int sumP = 0;
int sumO = 0;
Scanner stdin = new Scanner(System.in);
System.out.println("Enter a positive or negative integer: ");
while ((stdin.nextInt()) >= 0) {
if (stdin.nextInt() % 2 == 0)
sumP += stdin.nextInt();
else
sumO += stdin.nextInt();
}
System.out.println(sumP + " " + sumO);
stdin.close();
}
};
最佳答案
每次调用 stdin.nextInt() 时,它都会寻找另一个整数。为了避免这种情况,请在顶部设置一个等于输入的变量:
int myInt = stdin.nextInt();
if (myInt >= 0) {
if (myInt % 2 == 0)
sumP += myInt;
else
sumO += myInt;
}
System.out.println(sumP + " " + sumO);
stdin.close();
}
}
您也不要在最后一个花括号后面添加分号。如果您期望输入多个数字,您可以继续检查下一个数字,
while(stdin.hasNext()){
int myInt = stdin.nextInt();
}
关于java - 如何在java中的while循环中添加?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19086454/