【发布时间】:2017-11-19 20:20:57
【问题描述】:
我有一个程序,但问题是即使我告诉它停止它仍然运行。我已经告诉它在布尔变量变为假时停止运行,但即使在变量变为假之后,程序也会继续运行。我发现程序继续运行的唯一方法是在 while 语句中取出“=true”部分。那么为什么我需要把语句中的“=true”部分去掉才能让程序正常运行呢?
import java.util.Scanner;
public class EvenOdd {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
int num;
boolean continueLoop=true;
do {
try {
System.out.println("Enter an even number");
num=input.nextInt();
if(num%2==0)
System.out.println("That is an even number");
else
throw new IllegalArgumentException();
continueLoop=false;
}
catch(IllegalArgumentException ae) {
System.err.println(ae+"\nThat is a odd number");
}
} while(continueLoop=true);
input.close();
}
}
【问题讨论】:
-
continueLoop=true是一个赋值,你总是在该行中将变量设置为 true。查找基本的 java 教程会告诉你:docs.oracle.com/javase/tutorial/java/nutsandbolts/… -
删除
= true是适当的修复。比较someBoolean == true是多余的。只使用someBoolean就足够了。 -
仔细查看:while(continueLoop=true);
-
你的错误在这一行---> while(continueLoop==true);输入.close(); }
标签: java exception while-loop do-while