2017-08-12 141 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(); 
    } 
} 

我希望这可以说明您如何从文件中读取任何键值对并将其存储以供以后使用。