2017-08-12 77 views
0

我希望java中的代碼能夠讀取文本文件,在第一列中選​​擇一個值,然後在第二列中輸出相應的值,如下面的圖片。Java - 打印值映射到從文件中讀取的密鑰

我設法使用這裏顯示的代碼讀取文件,但我無法繼續。

public class readfile { 
    private Scanner s; 

    public static void main(String[] args) { 
     readfile r = new readfile(); 
     r.openFile(); 
     r.readFile(); 
     r.closeFile(); 
    } 

    public void openFile() { 
     try { 
      s = new Scanner (new File("filename.txt")); 
     } catch(Exception e) { 
      System.out.println("file not found "); 
     } 
    } 

    public void readFile() { 
     while(s.hasNext()) { 
      String a = s.next(); 
      String b = s.next(); 
      System.out.printf("%s %s\n",a, b);  
     } 
    } 

    public void closeFile() { 
     s.close(); 
    } 
} 

I would like to code that selects a value in first column and prints its corresponding value in the second column as show in this image

+0

沒有特定的語言,你可能只能遍歷數組,並檢查第一列中的瓦力,如果它相等寫第二列 –

+0

謝謝@MarekMaszay您的迴應。我編輯了我的帖子,使其更清晰。如果您在重新查看此帖後有任何建議,請與我分享。我在Java中相對較新。 –

+0

這兩列的映射在哪裏?他們是否在同一個文件?他們是否共享一條線,如果是這樣 - 用什麼分隔符來分隔列?如果他們不共用一條線,他們總是一個接一個地存在嗎? – Assafs

回答

0

以你的代碼作爲此基礎上(我試圖讓最起碼的變化)我建議你存儲在地圖讀取的值 - 這將讓你得到相應的價值很快。

public class readfile { 
    private Scanner s; 

    public static void main(String[] args) { 
     readfile r = new readfile(); 
     r.openFile(); 

     //tokens in a map that holds the values from the file 
     Map<String,String> tokens = r.readFile(); 
     r.closeFile(); 

     //this section just demonstrates how you might use the map 
     Scanner scanner = new Scanner(System.in); 
     String token = scanner.next(); 

     //This is a simple user input loop. Enter values of the first 
     //column to get the second column - until you enter 'exit'. 
     while (!token.equals("exit")) { 
      //If the value from the first column exists in the map 
      if (tokens.containsKey(token)) { 
       //then print the corresponding value from the second column 
       System.out.println(tokens.get(token)); 
      } 
      token = scanner.next(); 
     } 
     scanner.close(); 
    } 

    public void openFile() { 
     try { 
      s = new Scanner (new File("filename.txt")); 
     } catch(Exception e) { 
      System.out.println("file not found "); 
     } 
    } 

    //Note this change - the method now returns a map 
    public Map<String,String> readFile() { 
    Map<String, String> tokens = new HashMap<String,String>(); 
    while(s.hasNext()) { 
     String a = s.next(); 
     String b = s.next(); 
     tokens.put(a,b); //we store the two values in a map to use later 
    } 
    return tokens; //return the map, to be used. 
    }  

    public void closeFile() { 
     s.close(); 
    } 
} 

我希望這可以說明您如何從文件中讀取任何鍵值對並將其存儲以供以後使用。