我有这个输入文件:
6
8
ABBEJCDD
ULSCALAR
FUGLVRUT
STOUASTO
STOALGOT
LALGOSLU
8
SCALA
JAVA
ALGOS
ALGORITHM
SLUG
SLUR
GOES
TURTLE
当前,我正在做的是读取前两个项目(即int),并将它们添加到ArrayList中。然后,我只想读取接下来的6行(不包括“ 8”),并将它们添加到数组中。
我将如何修改我的代码?
Scanner fileScanner = null;
File inFile = new File("input.dat");
ArrayList<Integer> rc = new ArrayList<Integer>();
try {
fileScanner = new Scanner(inFile);
System.out.println("The input has been loaded successfully.");
while (fileScanner.hasNextInt()) {
int tempRowsCols = fileScanner.nextInt();
rc.add(tempRowsCols);
} // end while
while (fileScanner.hasNext()) {
System.out.print(fileScanner.next());
}
} // end try
catch (Exception e) {
System.out.println("Did not work.");
}
最佳答案
这个问题希望代码以其他方式读取数据。假设前两个值是整数,分别表示文本网格的高度和宽度。
// read the width and height
int height = scan.nextInt();
int width = scan.nextInt();
// build the 2D array to store the char grid.
char[][] chars = new char[height][];
for (int line = 0; line < height; line++) {
chars[line] = scan.next().toCharArray();
}
然后,您得到8来指示有8个单词,后跟单词:
// get the number of words to expect
int wordcount = scan.nextInt();
// make a place to store the words.
String[] words = new String[wordcount];
for (int i = 0; i < wordcount; i++) {
words[i] = scan.next();
}
这将为您提供2d char数组中的数据,以及String数组中的单词。