【发布时间】:2021-06-29 17:34:13
【问题描述】:
我是 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);
}
}
【问题讨论】:
-
异常发生在哪里?你有它的堆栈跟踪吗?
-
每次你想从控制台读取数据时,不需要构造一个新的 Scanner 实例。只需在开始时创建一次,然后每次要获取输入时使用相同的实例。
标签: java string runtime-error indexoutofboundsexception