从用户处获取字符串输入的另一种方法



我已经实现了以下代码,将这些值作为输入:-

3 6
CLICK 1
CLICK 2
CLICK 3
CLICK 2
CLOSEALL
CLICK 1

但是对于字符串输入,我尝试了nextLine(),但在这种情况下它不接受输入。如果我使用next(),那么它将CLICK1视为两个不同的字符串,因此当我将字符串拆分并解析为int时,我将得到ArrayIndexOutOfBoundsException。处理这些输入的替代方法是什么?

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()不扫描回车符号。在尝试解析下一个输入之前,您需要确保对其进行扫描。

例如:

import java.util.*;
public class TweetClose {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
sc.nextLine();
int k = sc.nextInt();
sc.nextLine();
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();
}
}

使用nextLine()导致的问题。您应该使用next(),因为您想要处理下一个令牌。

处理完所有令牌后,当前行的最后一个换行符仍在内存中。nextLine()返回换行符"n"。然后处理它:

String[] st = s.split(" ");
int y = Integer.parseInt(st[1]);

split函数返回一个只有一个元素的数组("n"),因此您不能解析st[1]。没有这样的元素,只有st[0]存在。

它将使用next()而不是nextLine(),因为next()跳过换行符并继续使用下一行的下一个标记。

这是一个很常见的错误,因为没有nextString()函数。

最新更新