I have to search the first line of a text file for two Int values that will be the dimensions of a 2D array. Here is what I have so far开发者_JAVA百科...Thanks!
try {
Scanner scan = new Scanner(f);
int rows = scan.nextInt();
int columns = scan.nextInt();
String [][] maze = new String[rows][columns];
}
One other way:
// read your file
File f = new File("file.txt");
// make sure your file really exists
if(f.exists()) {
// a buffered reader is standard for reading files in Java
BufferedReader bfr = new BufferedReader(new FileReader(f));
// read the first line, that's what you need
String line = bfr.readLine();
// assuming your integers are separated with a whitespace, use this splitter
// if they're separated with a comma, the use line.split(",");
String[] integers = line.split(" ");
// get the first integer
int i1 = Integer.valueOf(integers[0]);
// get the second integer
int i2 = Integer.valueOf(integers[1]);
System.out.println(i1);
System.out.println(i2);
// finally, close buffered reader to avoid any leaks
bfr.close();
}
I'll leave the exception handling up to you. You will have exceptions if your file doesn't exist, can't be read, or if first and second parts of the first line aren't integers. It's ok if they are negative.
Note: you didn't specify anything about how the first line looks like. I assumed in this code they are at the beginning, separated with a whitespace.
If they're not, then you can also use string splitting, but you'll have to check if every splitted part can be converted to an Integer. If you have 3 or more integers in the first line, there will be ambiguities. Hence, my assumptions.
精彩评论