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

How can i read inside loop in java without runtime error?

我是 java 的新手,我尝试用它解决一些问题(用于练习),但我遇到了运行时错误,不知道为什么,也不知道我应该搜索什么来知道为什么会这样。

这是我的代码。

当我将测试粘贴到控制台时发生运行时错误,但是当我编写它时却没有发生运行时错误

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

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);
    }
}

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

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);
}

要阅读 Codeforces 问题提供的文本,您需要做两件事:

  • 重复使用您创建的现有 Scanner(而不是为每个后续读取创建一个新的)
  • 使用Scanner.next instead of Scanner.nextLine

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

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

Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.

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

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