Grid from text to 2d array
import java.io.*;
import jav开发者_开发技巧a.util.*;
import java.awt.*;
public class FileInputExample2
{
static public void main(String[] args) throws IOException
{
int t;
BufferedReader filein;
filein = new BufferedReader (new FileReader("GridDATA.txt"));
int intGrid [] [] = new int [10] [10];
String inputLine = filein.readLine();
StringTokenizer st = new StringTokenizer(inputLine, " ");
for (int i=0; i<10; i++)
for (int j=0; j<10; j++)
{String eachNumber = st.nextToken();
intGrid [i] [j] = Integer.parseInt(eachNumber);
}
for (int i=0; i<10; i++)
for (int j=0; j<10; j++)
{
System.out.println( intGrid[i][j]);
}
}
}
this is what i have so far im trying to display this grid that i have the text file looks like this :
0 1 1 1 1 1 1 1 1 1
0 0 0 1 1 1 1 1 1 1
1 1 0 1 1 1 1 0 0 0
1 1 0 0 0 0 1 0 1 0
1 1 1 1 1 0 1 0 1 0
1 1 1 1 1 0 0 0 1 0
1 1 1 1 1 1 1 1 1 0
1 1 1 1 1 1 1 1 1 0
1 1 1 1 1 1 1 1 1 0
1 1 1 1 1 1 1 1 1 0
I have no idea why its not wokring. ultimatly i wil be makin a maze.
For one thing, System.out.println( intGrid[i][j]);
will print one grid element per line.
You probably want something more like
for (int i=0; i<10; i++) {
for (int j=0; j<10; j++)
{
System.out.print( intGrid[i][j]);
System.out.print(" ");
}
System.out.println("");
}
Note that we're using print
in the inner loop, not println. This will not perform a carriage return so the numbers will be on one line. After the inner loop, however, we execute a println
to perform the carriage return/newline.
public class FileInputExample2 {
static public void main(String[] args) throws IOException {
BufferedReader filein = new BufferedReader(new FileReader("GridDATA.txt"));
int intGrid[][] = new int[10][10];
Scanner st = new Scanner(filein);
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++)
intGrid[i][j] = st.nextInt();
}
for (int[] arr1d : intGrid)
System.out.println(Arrays.toString(arr1d));
}
}
精彩评论