我還在學習java編程,所以請原諒我缺乏知識。這可能是有史以來最簡單的事情,但在用戶輸入描述低于字符限制之前,我無法找到更好的方法讓checkTaskDescription方法回圈。到目前為止,這是我能夠做到的唯一方法,但它清楚地重復了輸入對話框兩次。
這是執行它的部分
do{
checkTaskDescription();
}
while (checkTaskDescription() == false);
這是正在執行的 checkTaskDescription 方法:
public boolean checkTaskDescription() {
taskDesc = JOptionPane.showInputDialog(null, "Please enter a short description of the task");
if (taskDesc.length() > 50) {
JOptionPane.showMessageDialog(null, "Please enter a task description of less than 50 characters.", "ERROR",3);
taskDesc = JOptionPane.showInputDialog(null, "Please enter a short description of the task");
return false;
}
JOptionPane.showMessageDialog(null, "Task successfully captured.");
return true;
}
uj5u.com熱心網友回復:
您需要使用方法呼叫的結果。
boolean ready = false;
do{
ready = checkTaskDescription();
} while ( ! ready );
這將進入 do 塊,將 ready 分配給 checkTaskDescription() 的回傳值,然后檢查它是否為 false。如果為假,則繼續回圈,直到為真。
你的 checkTaskDescription 也壞了。如果你第一次失敗,它會再次顯示對話框,然后總是回傳 false。
public boolean checkTaskDescription() {
taskDesc = JOptionPane.showInputDialog(null, "Please enter a short description of the task");
if (taskDesc.length() > 50) {
JOptionPane.showMessageDialog(null, "Please enter a task description of less than 50 characters.");
return false;
}
JOptionPane.showMessageDialog(null, "Task successfully captured.");
return true;
}
我更新了方法,因此當輸入失敗時它會“作業”,它會顯示一條錯誤訊息,然后回圈并再次顯示對話框。這就是為什么您應該驗證對話框中的資料,而不是在回圈中打開對話框。
uj5u.com熱心網友回復:
如果你做這樣的事情會容易得多
public String getTaskDescription() {
String taskDescription = "";
do {
taskDescription = JOptionPane.showInputDialog(null, "Please enter a short description of the task");
}
while (taskDescription.length() > 50);
return taskDescription;
}
當你設計你的方法時,盡量讓它們自成一體。現在您回傳一個標志并依靠呼叫方方法再次呼叫它,以防輸入無效。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/489652.html
