删除字符串中的最后一个输入,因此它不会显示在 showMessageDialog 中

deleting last input in a string so it does not show in showMessageDialog

我的程序需要一小部分帮助。我正在收集姓名列表,当你完成后,你输入 "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);
}