package CityDistance;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
public class CityDistance {
private ArrayList<String> city = new ArrayList<String>();
private int answer = 0;
HashMap<String, Integer> distance = new HashMap<String, Integer>();
public void input()
{
Scanner in = new Scanner(System.in);
String temp = null;
while ((temp = in.next()) != "###")
{
city.add(temp);
}
int number = city.size();
for ( int i = 0; i < number; i++ )
{
for ( int j = 0; j < number; j++ )
{
String key = "" + city.get(i) + city.get(j);
distance.put(key, in.nextInt());
}
}
in.close();
}
public int FindDistance(String A, String B)
{
String str = A + B;
answer = distance.get(str);
System.out.println(answer);
return answer;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
CityDistance cd = new CityDistance();
cd.input();
cd.FindDistance(in.next(), in.next());
in.close();
}
}
輸入如下:
aaa bbb ccc ###
0 1 2
1 0 3
2 3 0
aaa bbb
input 函數裡的第一個 while ,已經設定好了遇到 "###" 的輸入就停止往 city 裡加東西,但調試時發現 while 並沒有停止,反而把後面的0、1、2都添到 city 裡去了……
跪求大神解答!
import java.util.*;
public class CityDistance {
private List<String> city = new ArrayList<String>();
private int answer = 0;
private Map<String, Integer> distance = new HashMap<String, Integer>();
public void input()
{
Scanner in = new Scanner(System.in);
String temp = null;
System.out.println("請輸入城市(“###”結束輸入):");
/*
* 注意:字符串是一個對象,不是基本類型,不能使用==比較,要使用equals
*/
while (!(temp = in.next()).equals("###"))
{
city.add(temp);
}
int number = city.size();
for ( int i = 0; i < number; i++ )
{
for ( int j = 0; j < number; j++ )
{
String key = "" + city.get(i) + city.get(j);
System.out.print("請輸入"+city.get(i) + "<-->"+city.get(j)+"的距離:");
distance.put(key, in.nextInt());
}
}
/*
* 注意:不能關閉,否則的話之後即使在main函數裡有一個scanner,也不能使用
*/
//in.close();
}
public int FindDistance(String A, String B)
{
String str = A + B;
if(distance.containsKey(str)){
answer = distance.get(str);
return answer;
}
return 0;
}
public static void main(String[] args) {
CityDistance cd = new CityDistance();
cd.input();
Scanner in = new Scanner(System.in);
System.out.println("查詢城市間距離:");
System.out.print("輸入城市1:");
/*
* 注意:input()裡不要調用in.close(),否則這裡得不到輸入,你可以測試一下,加深下印象
*/
String A = in.next();
System.out.print("輸入城市2:");
String B = in.next();
System.out.println(A + "<-->"+B + "的距離:" + cd.FindDistance(A,B));
}
}