我想开始说这个项目我不能使用任何类型的List。我在线搜索过,所有建议通常都说是使用ArrayList。所以我需要帮助找到另一种方法来做到这一点。确定..
我有一个GUI,它有一个ComboBox,显示从文件中读取的城市列表。我有那个部分就好了。但是城市需要按字母顺序排列。这发生在这两个类
中ReadButton Listener类:
class ReadListener implements ActionListener {
public void actionPerformed(ActionEvent arg0)
{
Scanner cityData = null;
try
{
cityData = new Scanner(new File(CityGUI.this.inputFile.getText()));
}
catch (FileNotFoundException e)
{
CityGUI.this.inputMessage.setForeground(Color.RED);
CityGUI.this.inputMessage.setText("File not found");
}
cityData.nextLine();
//reads the file until there is no more data to be read
while (cityData.hasNextLine()) {
Scanner lineScanner = new Scanner(cityData.nextLine());
lineScanner.useDelimiter(",");
int zip = lineScanner.nextInt();
String cityName = lineScanner.next();
String state = lineScanner.next();
double lat = lineScanner.nextDouble();
double lon = lineScanner.nextDouble();
int time = lineScanner.nextInt();
String restOfLine = lineScanner.nextLine();
boolean dayLight;
if (restOfLine.charAt(1) == '1') {
dayLight = true;
} else {
dayLight = false;
}
City newCity = new City(zip, cityName, state, lat, lon, time, dayLight);
CityGUI.this.cityList.addCity(newCity);
}
CityGUI.this.inputMessage.setForeground(Color.BLUE);
CityGUI.this.inputMessage.setText("The cities have been read");
String[] cityNames = CityGUI.this.cityList.getCityNames();
//add the cities to the list displayed in the combo box
for (int i = 0; i < cityNames.length; i++) {
CityGUI.this.cityCombo.addItem(cityNames[i]);
}
}
}
和我的CityGroup课程:
public class CityGroup
{
private final int numCities = 30;
private City[] cityArray = new City[numCities];
private int count = 0;
//adds cities read from the file to an array
public void addCity(City newCity)
{
cityArray[count] = newCity;
count++;
}
//read the names from the cityArray and returns them when called
public String[] getCityNames()
{
String[] names = new String[numCities];
for (int i = 0; i < count; i++) {
names[i] = cityArray[i].getCityName();
}
return names;
}
public City getCity(String cityName)
{
for (int i = 0; i < numCities; i++) {
if (cityArray[i].getCityName().equals(cityName)) {
return cityArray[i];
}
}
return null;
}
}
.compareTo也没用。