2013-02-26 63 views
0

假设我在此格式的文件,如何读取文件,并使用扫描仪

的值存储在一个2维数组

我正在使用扫描仪类读取文件。我想将这些值存储在二维数组中,例如

y [0] [0] = 8,y [0] [1] = 15,y [1] [0] = 5 ,Y [2] [0] = 8。

我无法存储这样的值。我得到一个输出

y [0] [0] = 8,y [0] [1] = 15,y [0] [3] = 5,y [0] [4] = 8 。

我想知道如何在文件中找到(EOL)行尾,以便它自动存储在二维数组中。

public class gjd { 

public static void main(String[] args) { 

      java.io.File test2 = new java.io.File("c.txt"); 

      try 
      { 
       Scanner input = new Scanner(test2); 

       while (input.hasNextLine()){ 
        int y[][]=new int[10][10]; 
        for(int i=0;i<test2.length();i++) 
        { 
         for(int o=0;o<test2.length();o++) 
        { 
         y[i][o]=input.nextInt(); 


         System.out.println(y[i][o]); 


        } 

        } 

       } 
      } catch (Exception e){ 
      System.out.println("could not find file"); 
      } 

     } 
} 

回答

1

试试这个代码....

  java.io.File test2 = new java.io.File("C:/c.txt"); 
      Scanner input = new Scanner(test2); 
      String arr[][]=new String[5][5]; 
      int i=0,j=0; 
      while(input.hasNext()) 
      { 
       String val=input.nextLine(); 
       j=0; 
       if(val.contains(" ")) 
       { 
        String str[]=val.split(" "); 
        int cn=str.length; 
        while(cn>0) 
        { 
         arr[i][j]=str[j]; 
         cn--; 
         j++; 
        } 
       } 
       else 
        arr[i][j]=val; 
       i++; 
      } 

      for(int i1=0;i1<5;i1++) 
      { 
       for(int j1=0;j1<5;j1++) 
        if(arr[i1][j1] != null) 
        System.out.print(arr[i1][j1]); 
       System.out.println(); 
      } 
+0

真棒家伙,我能够得到我想要的输出。我开始非常喜欢java。谢谢。 – user2109988 2013-02-26 09:34:09

0

你不应该实例化一个数组每次都发现线路:

​​不应该在while循环。

你想要做什么与文件的长度:test2.length()

0

,你可以使用第二个扫描仪的工作线从第一扫描仪

,那么你可以检查已经解析,是否有另一种是另一个int类型该行,如果需要,设置一个默认值。