我正在尝试读取这种格式的输入
4 4
* . . .
. . . .
. * . .
. . . .
4 4
* * . .
. . . .
. . . .
. . * .
我能够读取前两个数字,但当我尝试读取符号时出现异常。我可以使用 BufferedReader 读取每一行并解析输入,但为什么不能使用扫描仪执行此操作?
这是我的代码
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextLine()) {
Scanner s = new Scanner(in.nextLine());
if (!s.hasNextLine())
break;
int x = s.nextInt(); // 4
int y = s.nextInt(); // 4
for (int i = 0; i <= x - 1; i++) {
for (int j = 0; j <= y - 1; j++) {
System.out.println(s.hasNext()); // false
String symbol = s.next(); //NoSuchElementException WHY?
}
}
}
}
}
最佳答案
当没有任何数字时,您不应该尝试读取数字。
你的循环,在伪代码中,看起来像
While there is a line available:
s = NextLine()
x = FirstInt(s)
y = SecondInt(s)
// Some other stuff
当您分配给 x
和 y
时,除了第一行之外没有可用的数字,因此您的应用程序崩溃。
与问题相匹配的更好的解决方案是
Scanner in = new Scanner(System.in);
if (!in.hasNextInt()) exitAndPrintError();
int rows = in.nextInt();
if (!in.hasNextInt()) exitAndPrintError();
int cols = in.nextInt();
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
if (!in.hasNext()) exitAndPrintError();
process(in.next());
}
}
此解决方案实际上不会检查太多错误,而是将所有错误报告留给您必须编写的某个 exitAndPrintError
函数。
作为旁注:如果您尝试 s.hasNext()
并且它返回 false,那么您应该会感到惊讶 s.next()
不抛出异常。这就是为什么 hasNext*
方法在 Scanner
上可用 - 它们让您有机会知道何时到达输入末尾,而不是尝试读取更多输入比可用的。
我将把它作为更新此代码以处理单个文件中的多组数据的练习,但这并不困难。您发布的代码中的关键错误是,如果您仅使用 in
中的一行创建扫描仪 s
,您将不会在其中找到多行结构s
正在处理的单行。
关于java - 为什么扫描仪不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14742408/