如何在没有运行时错误的情况下读取 java 中的内部循环?



我是 Java 的新手,并尝试用它解决一些问题(用于实践),但我遇到运行时错误,无法知道为什么或我应该搜索什么以了解为什么会这样。

这是我的代码。

将测试粘贴到控制台时发生运行时错误,但当我编写测试时,运行时未发生

这是问题的链接,如果这可以帮助您理解我的错误

https://codeforces.com/contest/1374/problem/C

import java.util.*;


public class Main {

public static void main(String[] args){
Scanner reader = new Scanner(System.in);
int t = reader.nextInt();
ArrayList<Integer> anss = new ArrayList<>();
for(int tst = 0; tst < t; tst++){
int n = new Scanner(System.in).nextInt();
String s = new Scanner(System.in).nextLine();
int ans = 0;
int open = 0;
for(int i = 0; i < n; i++){
if(s.charAt(i) == ')'){
if(open == 0) ans++;
else open--;
} else {
open++;
}
}
anss.add(ans);
}
for(int i : anss) System.out.println(i);
}
}

要阅读该文本,如Codeforce问题提供的那样,您需要做两件事:

  • 重复使用已创建的现有Scanner(而不是为每次后续读取创建新)
  • 使用Scanner.next而不是Scanner.nextLine

对于第一点,当Scanner开始解析InputStream时(例如,在调用nextInt时),它将消耗相当一部分流。在这种情况下,它会消耗整个流,因此在读取流时,创建在同一InputStream上运行的另一个Scanner将失败。

对于第二个,尽管nextLine的文档似乎表明将返回整行:

将此扫描程序推进到当前行以上,并返回跳过的输入。此方法返回当前行的其余部分,不包括末尾的任何行分隔符。位置设置为下一行的开头。

它实际上似乎忽略了第一个标记,即行的第一个非空格部分。在这种情况下,每行都没有空格,因此next将返回您需要的字符串。在一般情况下,看起来整条线都围绕着做这样的事情:

String s = reader.next() + reader.nextLine();

您不需要询问用户行长,因为您可以计算它:

public static void main(String[] args) throws Exception {
Scanner reader = new Scanner(System.in);
int t = reader.nextInt();
ArrayList<Integer> anss = new ArrayList<>();
for(int tst = 0; tst < t; tst++){
String s = new Scanner(System.in).nextLine();
int ans = 0;
int open = 0;
for(int i = 0; i < s.length(); i++){
if(s.charAt(i) == ')'){
if(open == 0) ans++;
else open--;
} else {
open++;
}
}
anss.add(ans);
}
for(int i : anss) System.out.println(i);
}

最新更新