[英]While loop doesn't loop in java
即使布尔值仍然为false,我在Java中的while循环也不会循环(我认为吗?)。
如果删除所有的“ mysqlStatus = true ”,它仍然不想循环。 我真的不明白怎么可能,因为我从来没有将布尔值切换为“ true”。
虽然这可能有些愚蠢,所以请先感谢您的帮助:)。
循环:
Connection conn;
Boolean mysqlStatus = false;
while(mysqlStatus.equals(false)) {
try {
Class.forName(driver).newInstance();
conTest = DriverManager.getConnection(host + dbName, username, password);
mysqlStatus = true;
} catch (SQLException e) {
// server offline
Alert alert = new Alert(AlertType.CONFIRMATION);
alert.setTitle("Database offline");
alert.setHeaderText("De MySQL database server is offline");
alert.setContentText("Start de server en probeer opnieuw.");
ButtonType buttonTypeOne = new ButtonType("Opnieuw controleren");
ButtonType buttonTypeCancel = new ButtonType("Exit", ButtonData.CANCEL_CLOSE);
alert.getButtonTypes().setAll(buttonTypeOne, buttonTypeCancel);
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == buttonTypeOne){
mysqlStatus = false;
alert.close();
} else {
System.exit(0);
}
} catch (Exception e) {
mysqlStatus = false;
ExceptionDialog cexD = new ExceptionDialog();
cexD.setStrError("Er is een onverwachte fout opgetreden.");
cexD.setException(e);
} finally {
try {
conTest.close();
} catch (SQLException e) {
mysqlStatus = false;
ExceptionDialog cexD = new ExceptionDialog();
cexD.setStrError("Er is een onverwachte fout opgetreden.");
cexD.setException(e);
}
}
}
你不做
mysqlStatus.equals(false)
在Java中。 不知道该怎么办。
你需要做
(!mysqlStatus)
检查条件。
从这里 :
当且仅当参数不为
null
且是一个表示与此对象具有相同布尔值的Boolean
对象时, java.lang.Boolean.equals(Object obj)返回true
。
现在, false
是原始的boolean
文字(它是true
或false
,不是Boolean
对象。 Boolean
对象可以是true
, false
或NULL
)
所以,当您这样做时会发生什么:
mysqlStatus.equals(false)
是你比较一个Boolean
对象mysqlStatus
与boolean
原始的文字false
(而不是Boolean
与对象false
值),因此它总是返回false
(因为mysqlStatus
是不一样的Boolean
对象为false
),因此你永远不进入while
循环。
这样做以比较mysqlStatus
与Boolean
对象是否为false
:
while(Boolean.FALSE.equals(mysqlStatus)) //also handle NULL
除了SQLException之类的ClassExceptionFoundException之类的任何Exception都会被Exception捕获并无限循环。 有通话中断等。
布尔值是基本类型布尔值的对象包装器类。
boolean mysqlStatusVastgesteld = false;
while (!mysqlStatusVastgesteld) {
我通过制作一个检查状态的函数来修复了它。
public Boolean checkStatus() {
try {
Class.forName(driver).newInstance();
Connection conTest = DriverManager.getConnection(host + dbName, username, password);
return true;
} catch (Exception e) {
// server offline
return false;
}
}
我还做了一个while循环,运行此函数,直到返回true。 如果返回false,则会出现一个对话框,要求重试或退出。
现在一切正常。 这是一个奇怪的问题,但感谢大家的帮助! 我的代码中有多个错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.