2012-11-14 86 views
1

檢索一個匹配數組存儲所有的信息,我覺得這個程序真的很接近工作。我知道它不整潔,我會馬上清理它!問題在最底層。從用戶輸入的字符串和第一個字符串String [] []

public class FoodFacts 
{ 
    private static BufferedReader textIn; 
    private static BufferedReader foodFacts; 
      static int numberOfLines = 0; 
       static int NUM_COL = 7; 
      static int NUM_ROW = 961; 
      static String [][] foodArray = new String[NUM_ROW][NUM_COL]; 
     public static String fact; 
    // Make a random number to pull a line 
    static Random r = new Random(); 




    public static void main(String[] args) 
     { 
      try 
      { 

       textIn = new BufferedReader(new InputStreamReader(System.in)); 
       foodFacts= new BufferedReader(new FileReader("foodfacts.csv")); 
       Scanner factFile = new Scanner(foodFacts); 
       List<String> facts = new ArrayList<String>(); 

       // System.out.println("Printing out your array!"); 
       while (factFile.hasNextLine()){ 
       fact = factFile.nextLine(); 
       StringTokenizer st2 = new StringTokenizer(fact, ",") ; 

       while (st2.hasMoreElements()){ 
        for (int j = 0; j < NUM_COL ; j++) { 
        foodArray [numberOfLines][j]= st2.nextToken(); 
        //System.out.println("Foodarray at " + " " + numberOfLines + " is " +foodArray[numberOfLines][j]); 
        } 
        } 
        numberOfLines++; 
        } 

System.out.println("Please type in the food you wish to know about."); 
       String request; //user input 
       request = textIn.readLine(); 
       System.out.println ("You requested" + request); 

問題從這裏開始!

for (int i = 0; i < NUM_ROW ; i++) 
        { 
if (foodArray[i][0] == request) 
          for (int j = 0 ; j < NUM_COL ; j++) 
         System.out.println (foodArray[i][j]); //never prints anything 
         } 

        } 
        catch (IOException e) 
        { 
        System.out.println ("Error, problem reading text file!"); 
        e.printStackTrace(); 
        } 

      } 
    } 

我想測試它的終端,其中foodArray [6] [0]應該匹配輸入全麥維穀物

回答

2

在你的最後for循環,你是比較使用==您的字符串在if construct中,這會給你不正確的結果,因爲==比較了字符串引用,這可能是不同的,因爲這兩個引用指向不同的字符串對象。

使用equals方法來比較字符串內容: -

if (foodArray[i][0].equals(request)) 

如果要比較其content你應該總是使用equals方法與任何object

看看這個帖子: - How do I Compare strings in Java瞭解更多詳情。

+0

謝謝你謝謝! –

+0

@FredV ..不客氣:) –

相關問題