- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个 3x3 矩阵输入流,我在其中计算两个主对角线总和的绝对差。下面的例子:
11 2 4
4 5 6
10 8 -12
应该给我 15 的结果,因为:
| 11 + 5 - 12 | 11 + 5 - 12 - | 4 + 5 + 10 |
= | 4 | - | 19 |
= 15
我的代码如下:
public class Solution {
static int diagSumL(int lines, Scanner in) {
int currSum;
currSum = 0;
for (int i = 0; i < lines; i++) {
for (int j = 0; j < i; j++) {
in.nextInt();
}
currSum += in.nextInt();
System.out.println(currSum);
if (in.hasNextLine() == true) {
in.nextLine();
}
}
return currSum;
}
static int diagSumR(int lines, Scanner in) {
int currSum, index;
currSum = 0;
for (int i = lines; i > 0; i--) {
for (int j = 1; j < i; j--) {
in.nextInt();
}
currSum += in.nextInt();
System.out.println(currSum);
if (in.hasNextLine() == true) {
in.nextLine();
};
}
return currSum;
}
static int absDiff(int a, int b) {
return Math.abs(a) + Math.abs(b);
}
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner in = new Scanner(System.in);
int lines, sumDiagL, sumDiagR;
lines = in.nextInt();
sumDiagL = diagSumL(lines, in);
in.close();
in = new Scanner(System.in);
sumDiagR = diagSumR(lines, in);
int result = absDiff(sumDiagL, sumDiagR);
System.out.println(result);
}
}
我的代码错误位于第三行到最后一行,其根源在于我的 diagSumR 方法试图调用 in.intNext() ,其中错误是:
Exception in thread "main" java.util.NoSuchElementException
我想做的是重置扫描仪,这样我就可以重新开始并从头开始重新读取扫描仪(这样我就可以计算另一条对角线的总和)。我使用 close() 是否错误?(网上使用 close() 的每个例子都是这样的)
是否可以使用 Scanner 类中的 reset() 作为替代方案,如果可以的话,如何实现?
最佳答案
这不起作用,因为当您使用 close()
关闭扫描仪时,它不仅“关闭”对象,而且还“关闭”底层的 System.in
。因此,即使您创建一个新的 Scanner 实例,底层的 System.in 也会关闭,因此您会收到异常。可以在调用 close()
之前和之后使用 System.in.available();
进行检查。此外,流关闭后也无法重新打开。
请关注documentation .
另一方面,if its underlying readable also implements the Closeable interface then the readable's close method will be invoked
System.in
返回 InputStream它实现了Closeable、AutoCloseable
。
即使您不想将矩阵存储在内存中,您的解决方案也不是最佳的,因为一旦从 System.in
读取某些内容,它就需要用户输入矩阵两次无法使用扫描仪
重新读取它!您拥有所有数据,因此您实际上可以一次性计算两个总和,存储 2 个总和变量,因为无论如何您都在读取所有数字。只需注意哪个数字被添加到哪个 sum 变量即可。
既然您无论如何都要传递该 Scanner
实例,我看不出有任何理由 close()
它并在调用 diagSumR< 之前重新初始化
,只需在方法结束时关闭它即可。正如我提到的,缺点是您需要再次手动输入矩阵。
关于java - 如何使用 close() 或 reset() 从头开始读取扫描仪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31824145/
我需要用这样的数据构建一个表: ┌────────┬───────────┬────────┐ │ ID │ Name │ Age │ ├────
我是一名优秀的程序员,十分优秀!