我正在尝试测试输入是奇数还是偶数。该程序说如果输入是连续的,直到输入是奇数。当它是奇数时,它会停止程序。但该计划并未停止。有人有什么想法吗?
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;
}
}
答案 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
while
和if
它不会做你想做的事答案 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;
}