试图测试输入是奇数还是偶数

时间:2017-12-29 20:41:31

标签: java methods while-loop

我正在尝试测试输入是奇数还是偶数。该程序说如果输入是连续的,直到输入是奇数。当它是奇数时,它会停止程序。但该计划并未停止。有人有什么想法吗?

private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
    while (isEven()) {
        if (isEven()) {
            isEven();
        } else {
            System.out.println(" You added an odd number, done!");
            return;
        }
    }
}
public static boolean isEven(){
    int a = scanner.nextInt();
    if (a%2 ==0){
        System.out.println("You added an even number, go on");
    }
    return true;
}

}

2 个答案:

答案 0 :(得分:1)

您最好简化所有这些,您不需要多次调用您的方法:

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    while (writeAndCheckEven(Integer.parseInt(scanner.nextLine()))) {
        System.out.println("You added an even number, go on");
    }

    System.out.println("You added an odd number, done!");
}

private static boolean writeAndCheckEven(int number) {
    return number % 2 == 0;
}
  • 如果
  • 之后没有更多代码,则不需要使用return
  • 您可以直接在参数
  • 中使用scanner
  • 不要同时使用whileif它不会做你想做的事

答案 1 :(得分:0)

您应该重写此代码,因为代码包含不正确的逻辑。 根据您的要求更正代码:

private static Scanner scanner = new Scanner(System.in);

public static void main(String[] args) {
    while (true) {
        int number = scanner.nextInt();
        if (isEven(number)) {
            System.out.println("You added an even number, go on");
        } else {
            System.out.println(" You added an odd number, done!");
            return;
        }
    }
}

private static boolean isEven(int number) {
    return number % 2 == 0;
}