从文件中扫描二维字符串数组
Scanning 2D String Array From a File
Scanner input = null;
try {
input = new Scanner (new File(filename));
} catch (FileNotFoundException ex) {
Logger.getLogger(Puzzle.class.getName()).log(Level.SEVERE, null, ex);
}
int m = 4;
int n = 4;
Puzzle = new String [m][n];
while (input.next()!=null){
for (int i=0;i<m;i++){
for (int j=0;j<n;j++){
Puzzle[i][j]= input.next();
System.out.println(Puzzle[i][j]);
}
}
}
I have a little problem with this piece of code. as I scan the input to put my puzzle array it skips the first string. for example in the first line, lets assume the 4 letter "A B C D" are on. It skips the "A" and continues with "B". I know maybe its too easy for you guys, but as a begginner I kinda need your help.
您在 while 循环的每次迭代中消耗了多个令牌 - 当您在循环条件(未使用)中调用 next()
时消耗一个令牌,当您调用 next()
时消耗多个令牌在 for 循环(您存储的)内。
您应该更改代码的逻辑。你不需要 while 循环。
例如:
boolean done = false;
for (int i=0;i<m && !done;i++){
for (int j=0;j<n && !done;j++){
Puzzle[i][j]= input.next();
if (Puzzle[i][j] == null)
done = true;
System.out.println(Puzzle[i][j]);
}
}
Scanner input = null;
try {
input = new Scanner (new File(filename));
} catch (FileNotFoundException ex) {
Logger.getLogger(Puzzle.class.getName()).log(Level.SEVERE, null, ex);
}
int m = 4;
int n = 4;
Puzzle = new String [m][n];
while (input.next()!=null){
for (int i=0;i<m;i++){
for (int j=0;j<n;j++){
Puzzle[i][j]= input.next();
System.out.println(Puzzle[i][j]);
}
}
}
I have a little problem with this piece of code. as I scan the input to put my puzzle array it skips the first string. for example in the first line, lets assume the 4 letter "A B C D" are on. It skips the "A" and continues with "B". I know maybe its too easy for you guys, but as a begginner I kinda need your help.
您在 while 循环的每次迭代中消耗了多个令牌 - 当您在循环条件(未使用)中调用 next()
时消耗一个令牌,当您调用 next()
时消耗多个令牌在 for 循环(您存储的)内。
您应该更改代码的逻辑。你不需要 while 循环。
例如:
boolean done = false;
for (int i=0;i<m && !done;i++){
for (int j=0;j<n && !done;j++){
Puzzle[i][j]= input.next();
if (Puzzle[i][j] == null)
done = true;
System.out.println(Puzzle[i][j]);
}
}