在我的程序中需要帮助。我会收集一个名称列表,完成后输入“ DONE”。需要消息对话框的帮助,我也不想将“ DONE”作为输出。
import javax.swing.JOptionPane;
public class IST_trasfer_test {
public static void main(String [] args) {
String stud_Name = "";
boolean student_Name = true;
String name_list = "";
while(student_Name) {
stud_Name = JOptionPane.showInputDialog("Enter Student name. Type 'DONE' when finished.");
if (stud_Name.equals("")) {
JOptionPane.showMessageDialog(null,"Please enter a name.");
student_Name = true;
}
name_list += stud_Name + "\n";
if (stud_Name.equals("DONE")) {
student_Name = false;
}
}
JOptionPane.showMessageDialog(null, name_list);
}
}
最佳答案
更改此行或您的代码:
if (stud_Name.equals("DONE")) {
// if is equal to 'DONE' then do not add to the name_list
student_Name = false;
} else {
name_list += stud_Name + "\n";
}
只需将
name_list += stud_Name + "\n";
代码行放入else
子句或者您也可以像这样简化它:
student_name = stud_Name.equals("DONE");
if (student_name) {
// if is not equal to 'DONE' then add to the name_list
name_list += stud_Name + "\n";
}
并做更多简化:
student_name = stud_Name.equals("DONE");
name_list += student_name ? stud_Name + "\n"; : "";
或者,您也可以如下编辑整个代码:
public static void main(String[] args) throws Exception {
String stud_Name = "";
String name_list = "";
while(true) {
stud_Name = JOptionPane.showInputDialog("Enter Student name. Type 'DONE' when finished.");
if (stud_Name.equals("")) {
JOptionPane.showMessageDialog(null,"Please enter a name.");
continue;
}
if (stud_Name.equalsIgnoreCase("DONE")) {
// ignore case
break;
}
name_list += stud_Name + "\n";
}
JOptionPane.showMessageDialog(null, name_list);
}