2015-10-26 121 views
1

我正在嘗試從二維數組中讀取。 這段代碼的功能是首先將.txt文件內容存儲到2d數組中,每個元素一行。然後將用戶輸入與每個陣列進行比較,尋找相似之處。任何相似性將被存儲在另一個數組中。從二維數組中讀取線條

這裏的東西是比較部分不起作用。任何提示爲什麼?

謝謝。

import java.awt.Point; 
import java.io.File; 
import java.util.Arrays; 
import java.io.FileNotFoundException; 
import java.util.Scanner; 

public class Main { 
    static int RowCheck =0; 
    static int C_Row = 0; 
    static int S_Row = 0; 


    static String lexicon[][] = new String[3000][10]; 
    static String results[][] = new String[100][10]; 


    private static String find2DIndex(Object[][] array, Object search) { 

     if (search == null || array == null) return null; 

     for (int rowIndex = 0; rowIndex < array.length; rowIndex++) { 
      Object[] row = array[rowIndex]; 
      if (row != null) { 
       for (int columnIndex = 0; columnIndex < 2; columnIndex++) { 
       if (search.equals(row[columnIndex])) { 

        for(int i=0; i<2; i++) 
          for(int j=0; j<=10; j++) 
          lexicon[i][j]=results[i][j]; 

         return Arrays.deepToString(results); 
       } 
       } 
      } 
     } 
     return null; // value not found in array 
    } 


    public static void main(String[] args) throws FileNotFoundException { 

     File testlex = new File("C:\\Users\\Harry\\Documents\\testlex.txt"); 
     File testlex2 = new File("C:\\Users\\Harry\\Documents\\textlex2.txt"); 


     Scanner cc = new Scanner(testlex2); 
     Scanner sc = new Scanner(testlex); 

     while (sc.hasNextLine()){ 
      int column = 0; 
      String line = sc.nextLine(); 
      sc.useDelimiter("/ *"); 
      if (line.isEmpty()) 
       continue; 

      C_Row = C_Row + 1; 
      column = 0; 

      String[] tokens = line.split("\\s"); 

      for (String token : tokens) { 
       if (token.isEmpty()) 
        continue; 
       lexicon[C_Row][column] = token; 
       column++; 
      } 
     } 

     while (cc.hasNextLine()){ 
      int column = 0; 
      String line = cc.nextLine(); 
      cc.useDelimiter("/ *"); 
      if (line.isEmpty()) 
       continue; 

      S_Row = S_Row + 1; 
      column = 0; 
      String[] tokens = line.split("\\s"); 
      for (String token : tokens) { 
       if (token.isEmpty()) 
        continue; 

       lexicon[S_Row][column] = token; 
       column++; 
      } 
     } 

     sc.close(); 
     cc.close(); 

     find2DIndex(lexicon, "abash"); 
     System.out.println(C_Row); 

    }  
} 

回答

0

這條線將比較searchrow[columnIndex]作爲Object類型的對象。

if (search.equals(row[columnIndex])) 

因此它會比較參考。您似乎想比較String對象的內容。有兩種方法可以修改find2DIndex

  1. 更改簽名

    private static String find2DIndex(String[][] array, String search) 
    

    String

  2. 把它替換Object任何發生在該功能爲通用方法

    private static <T> String find2DIndex(T[][] array, T search) 
    

    ,並更換在函數中出現ObjectT

在這兩種情況下equals現在是String的方法。