简体   繁体   中英

how to Read a file and store the values in a 2-Dimensional Array using Scanner

Suppose I have a file in this format,

8 15

5

8

16

89

I am using Scanner class for reading the file. I want to store these values in a 2-dimensional array, for example

y[0][0]=8,y[0][1]=15,y[1][0]=5,y[2][0]=8.

I am not able to store the values like this. I am getting an output

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

I like to know how can I find (EOL)end of line in the file, so that it automatically stores in 2-D array.

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");
           }

        }
}

Try this code....

           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();
            }

You should not be instantiating an array every time you find a line:

int y[][] = new int[10][10]; should not be in the while loop.

And what are you trying to do with the length of the file: test2.length() ?

you could use a second scanner working with the line having parsed from the first scanner

then you can check, whether there is another another int in the line, set a default value if needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM