acemi
acemi

Reputation: 50

How can I convert a string in a file into an array?

I have a .txt file and it has some numbers like

0,3,4, ... 9

................

1,2,5, ... 6

This is a sudoku design, I want to take this into an array

 Scanner in = new Scanner (new File ("sudoku1.txt")); //here I specified the target of the file like C:\\...
 for(int i=0; i<9; i++){
   for(int j=0; j<9; j++){
       String n = in.next();
     grid [i][j] = Integer.parseInt(n);
   }
 }
System.out.println(grid);

when I try to see the array, it give an error because of the " , " in the text file, if I delete commas and put spaces instead of commas, it works but even it shows me only 1 row and it does not work correctly.

Upvotes: 0

Views: 124

Answers (2)

The_Cute_Hedgehog
The_Cute_Hedgehog

Reputation: 1340

Scanner can use other delimiters. The default one matches the whitespaces.

Here is an example.

String myDelimiterGroup = "[,\\r\\n]"; // a pattern definition
Scanner scanner = new Scanner(yourFile).useDelimiter(myDelimiterGroup);

Hope it helps.

Upvotes: 2

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79105

Do it as follows:

Scanner in = new Scanner (new File ("sudoku1.txt"));
for(int i=0; i<9 && in.hasNextLine(); i++){
    String []nums = in.nextLine().split(",");
    for(int j=0; j<nums.length; j++){
        String n = nums[j].trim();
        grid [i][j] = Integer.parseInt(n);
    }
}
System.out.println(Arrays.deepToString(grid));

Upvotes: 2

Related Questions