简体   繁体   English

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

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

need help with a short bit of my program. 在我的程序中需要帮助。 Im gathering a list of names and when you're done you type "DONE." 我会收集一个名称列表,完成后输入“ DONE”。 need help with the message dialog i dont want "DONE" to be an output as well. 需要消息对话框的帮助,我也不想将“ 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);
    }
}

Change this line or your code: 更改此行或您的代码:

 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";
  }

Just put name_list += stud_Name + "\\n"; 只需name_list += stud_Name + "\\n"; line of code into else clause 代码行插入else子句

Or You can also simplify it like this: 或者您也可以像这样简化它:

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";
}

And do more simplifying: 做更多简化:

student_name = stud_Name.equals("DONE");
name_list += student_name ? stud_Name + "\n"; : "";

Or also you can edit your entire code as below: 或者,您也可以如下编辑整个代码:

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM