gpt4 book ai didi

java - 删除字符串中的最后一个输入,使其不会显示在 showMessageDialog 中

转载 作者:行者123 更新时间:2023-12-01 10:21:53 24 4
gpt4 key购买 nike

需要有关我的程序的一小部分的帮助。我正在收集姓名列表,完成后输入“完成”。需要消息对话框的帮助,我不希望“完成”也成为输出。

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

关于java - 删除字符串中的最后一个输入,使其不会显示在 showMessageDialog 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35544603/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com