I'm currently stuck on trying to figure out why my Array values aren't diplaying in the dialog box. I am doing an assignment whose details are:
"Write a program named TallestBuildingLookupthat contains an array of 10 TallestBuildingobjects and fill in it with the data given above accordingly. Then use dialog boxes to accept a building name and display the building’s location, height, and stories. If a match is not found, display an error message that includes the invalid name and allow the user to search for a new building name."
My main issue is getting my array values to display from my toString() method, and handling the exception when I don't receive a name in the array. Specifically, getting the dialog box to loop to re-enter a name value and recheck the array. Any help would be greatly appreciated.
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.");
}
}
}
}
Try this:
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);
}