2015-03-13 39 views
-2

我有一個arrayList的問題。 這是我的arrayList列表的代碼ArrayList問題,沒有值出來

我知道我的arrayList方法有一些問題,但我無法發現它。

在主類

private static void displayAllToursCountry() 
    { 
     System.out.print("Please enter the name of the country: "); 
     String country = sc.next(); 

     while (country == "") 
     { 
      System.out.print("Please enter a valid country name: "); 
      country = sc.next(); 
     } 
     System.out.println("Country:" + country); 
     System.out.println(ta1.countryList(country)); 
    } 

爲什麼ArrayList中

public ArrayList<Tour> countryList(String country) 
    { 
     ArrayList<Tour> newList = null; 
     switch (country) 
     { 
     case "Indonesia": 
      country = "IN"; 
      break; 
     case "Thailand": 
      country = "TH"; 
      break; 
     case "Singapore": 
      country = "SI"; 
      break; 
     case "Brunei": 
      country = "BR"; 
      break; 
     case "Philipines": 
      country = "PH"; 
      break; 
     case "Vietnam": 
      country = "VI"; 
      break; 
     case "Laos": 
      country = "LA"; 
      break; 
     case "Myammmar": 
      country = "MY"; 
      break; 
     case "Malaysia": 
      country = "MS"; 
      break; 
     } 
     if(TList.indexOf(country)!= 1) 
     { 
      return newList; 
     } 

     return newList; 

    } 

方法有沒有值出來? 我在哪裏做錯了?謝謝

+1

請澄清我們的代碼究竟是如何行爲不端。 「沒有價值出來」是什麼意思?究竟發生了什麼?另外,不要使用'=='或'!='比較字符串。改爲使用「equals(...)」或「equalsIgnoreCase(...)」方法。理解'=='檢查兩個*對象*是否相同,而不是你感興趣的。另一方面,方法檢查兩個字符串是否具有相同順序的相同字符,這是重要的這裏。 – 2015-03-13 15:18:27

+3

'while(country ==「」)'== bad。 [如何比較Java中的字符串](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – kolossus 2015-03-13 15:18:48

+0

確實,使用'while(「」。equals(country)) ' – EpicPandaForce 2015-03-13 15:26:20

回答

7

你沒有把任何東西放入ArrayList。

你只是在做

ArrayList<Tour> newList = null; 

然後return newList;

它甚至沒有初始化。

你應該初始化:ArrayList<Tour> newList = new ArrayList<>() 然後放了一些要素:newList.add(myTour);