java - 从用户获取字符串输入的替代方法
问题描述
我已经实现了以下代码,它将这些值作为输入:-
3 6
CLICK 1
CLICK 2
CLICK 3
CLICK 2
CLOSEALL
CLICK 1
但是为了获取字符串输入,我尝试了 nextLine() 但在这种情况下它不接受输入。如果我使用 next() 则它将CLICK
and1
视为两个不同的字符串,所以ArrayIndexOutOfBoundsException
当我拆分字符串并将其解析为 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();
}
}
解决方案
使用引起的问题nextLine()
。您应该next()
改用,因为您想处理下一个令牌。
处理完所有标记后,当前行的最终换行符仍在内存中。nextLine() 返回该换行符“\n”。然后你处理它:
String[] st = s.split(" ");
int y = Integer.parseInt(st[1]);
split 函数返回一个只有一个元素的数组(“\n”),因此您无法解析 st[1]。没有这样的元素,只有 st[0] 存在。
它将与 next() 而不是 nextLine() 一起使用,因为 next() 跳过换行符并继续下一行的下一个标记。
这是一个非常常见的错误,因为没有 nextString() 函数。
推荐阅读
- html - 有没有办法让使用列表创建的导航栏具有粘性?
- apache-spark - Spark 数据帧到 Redshift 中的 SQL 创建表语句
- swift - SFSpeechRecognizer 不允许设备区域设置上的非系统
- java - 无法在 Java 应用程序中实现 DAO 设计模式
- python-3.x - 是否可以“自定义”python?
- dictionary - Ansible 构建字典列表并附加到字典中的列表
- reactjs - setState 到嵌套对象删除值
- javascript - 如何切换 React 列表中的按钮?
- swiftui - Image view 如何在 SWiftUI 中通过 URL 显示照片?
- javascript - Safari — 在前几个之后无法创建振荡器