gpt4 book ai didi

java - 我如何让我的 Java 扫描器从这个文件中读取这些字符串?

转载 作者:行者123 更新时间:2023-11-30 07:05:59 24 4
gpt4 key购买 nike

我有这个输入文件:

6
8
ABBEJCDD
ULSCALAR
FUGLVRUT
STOUASTO
STOALGOT
LALGOSLU
8
SCALA
JAVA
ALGOS
ALGORITHM
SLUG
SLUR
GOES
TURTLE

目前,我用它做的是读取前两项(整数),并将它们添加到 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();
}

这将为您提供二维字符数组中的数据,以及字符串数组中的单词....

关于java - 我如何让我的 Java 扫描器从这个文件中读取这些字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26132059/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com