java - 如何在java中的while循环中添加?

标签 java while-loop

感谢您查看我的代码。 我正在学习 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/

相关文章:

java - 如何为java方法应用装饰器

java - Thread.sleep() 在 while 循环中

java - 如何循环直到得到正确答案?

c++ - 限制项目条目 C++

java - 从另一个 servlet 调用 servlet

java - 为什么 slf4j 记录器有时会打印出父线程,即使代码应该由子线程执行?

python - 将 for 循环转换为 while 循环

bash 命令在 while 循环中重定向标准输入(使用 sed)

java - 批处理运行java,找不到类

java - 使用Java读取远程MP3文件的ID3标签