【发布时间】:2021-02-14 15:01:38
【问题描述】:
我已经实现了以下将这些值作为输入的代码:-
3 6
CLICK 1
CLICK 2
CLICK 3
CLICK 2
CLOSEALL
CLICK 1
但是为了接受字符串输入,我尝试了 nextLine() 但在这种情况下它没有接受输入。如果我使用 next() 那么它将 CLICK 和 1 视为两个不同的字符串,所以我得到 @987654324 @ 因为我正在拆分字符串并将其解析为 int。处理此类输入的替代方法是什么?
import java.util.*;
public class TweetClose {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
int open = 0;
int a[] = new int[50];
for (int i = 1; i <= n; i++) {
a[i] = 0;
}
for (int i = 0; i < k; i++) {
String s = sc.nextLine();
if (s.equals("CLOSEALL")) {
open = 0;
for (int j = 1; j <= n; j++) {
a[j] = 0;
}
} else {
String[] st = s.split(" ");
int y = Integer.parseInt(st[1]);
if (a[y] != 1) {
a[y] = 1;
open++;
}
}
System.out.println(open);
}
sc.close();
}
}
【问题讨论】:
-
除了在
sc.nextInt()之后使用sc.nextLine()的问题之外,ArrayIndexOutOfBoundsException还有其他可能的原因,其中数组a是使用固定大小创建的,然后从未经验证的用户索引应用输入:for (int i = 1; i <= n; i++)或for (int j = 1; j <= n; j++)- 如果n >= 50; CLICK 后解析数字时的类似问题:int y = Integer.parseInt(st[1]); if (a[y] != 1): ify>=50