我目前一直在试图找出为什么我的数组值没有在对话框中显示。我正在做一项作业,其详细信息是:
“编写一个名为 TallestBuildingLookup 的程序,其中包含 10 个 TallestBuilding 对象的数组,并相应地填充上面给出的数据。然后使用对话框接受建筑物名称并显示建筑物的位置、高度和楼层。如果匹配,则为未找到,则显示一条包含无效名称的错误消息,并允许用户搜索新的建筑物名称。”
我的主要问题是从 toString() 方法获取要显示的数组值,并在数组中没有收到名称时处理异常。具体来说,让对话框循环以重新输入名称值并重新检查数组。任何帮助将不胜感激。
import javax.swing.*;
public class TallestBuildingLookup {
static class TallestBuilding{
private String name;
private String city;
private int height;
private int stories;
public TallestBuilding(String name, String city, int height, int stories) {
this.name = name;
this.city = city;
this.height = height;
this.stories = stories;
}
public String getName(){
return this.name;
}
public String toString(){
return this.name + " of " + this.city + ", "+ this.stories + "stories/" + this.height + " feet high." ;
}
}
public static void main(String[] args){
TallestBuilding[] tallestbuilding = new TallestBuilding[10];
tallestbuilding[0] = new TallestBuilding("One World Trade Center", "New York", 1776, 104);
tallestbuilding[1] = new TallestBuilding("Willis Tower", "Chicago", 1451, 108);
tallestbuilding[2] = new TallestBuilding("Empire State", "New York", 1250, 102);
tallestbuilding[3] = new TallestBuilding("Bank of America Tower", "New York", 1200, 55);
tallestbuilding[4] = new TallestBuilding("Aon Center", "Chicago", 1136, 83 );
tallestbuilding[5] = new TallestBuilding("John Hancock Center", "Chicago", 1127, 100);
tallestbuilding[6] = new TallestBuilding("Wells Fargo Plaza", "Houston", 992,71 );
tallestbuilding[7] = new TallestBuilding("Comcast Center", "Philidelphia", 974, 57 );
tallestbuilding[8] = new TallestBuilding("Columbia Center", "Seattle", 967, 76);
tallestbuilding[9] = new TallestBuilding("Key Tower", "Clevland", 947, 57);
String entry = JOptionPane.showInputDialog("Enter a builing name");
String name = (String) entry;
System.out.println(name);
for (int i=0; i<10; i++){
if(name == tallestbuilding[i].getName() ){
JOptionPane.showInputDialog(null, tallestbuilding[i] );
}
else{
JOptionPane.showInputDialog("Sorry - no "+ name + " was found.");
}
}
}
}
最佳答案
试试这个:
TallestBuilding tallestBuilding = null;
for (int i=0; i<10; i++){
if(name.equals(tallestbuilding[i].getName())){
tallestBuilding = tallestbuilding[i];
break;
}
}
if(tallestBuilding == null) {
JOptionPane.showInputDialog("Sorry - no "+ name + " was found.");
} else {
JOptionPane.showMessageDialog(null, tallestBuilding);
}
- 不要使用“==”来比较字符串,因为它比较的是引用,而不是它本身的值。检查Java String.equals versus ==
- 使用 MessageDialog 向用户显示值,而不是 InputDialog
- 您应该在显示用户后中断for循环
- 您应该保存在临时引用中找到的对象,以便稍后显示它。
关于java - 如何通过用户输入显示JOptionPane,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40938944/