【发布时间】:2021-10-10 22:34:15
【问题描述】:
由于某种原因,
query = sc.nextLine();代码返回查询""用于删除部分。 这样第二个代码块不会执行并输出错误的列表(由于 Delete 0,不会删除列表的第一个索引)。任何想法为什么第二个查询没有从 sc.nextLine() 分配?
public static void main(String[] args) {
final int QUERY_LIMIT = 2;
Scanner sc = new Scanner(System.in);
String query = "";
String insert = "Insert";
String delete = "Delete";
int initial = sc.nextInt();
List<Integer> list = new ArrayList<>();
List <Integer> insertList = new ArrayList<>();
for (int i = 0; i< initial; i++){
list.add(i, sc.nextInt());
}
int numberOfQueries = sc.nextInt();
while (numberOfQueries > 0) {
query = sc.nextLine();
if (insert.equals(query)) {
for (int y = 0; y < QUERY_LIMIT; y++) {
insertList.add(y, sc.nextInt());
}
int insertIndex = insertList.get(0);
int insertValue = insertList.get(1);
list.add(insertIndex,insertValue);
} else if (delete.equals(query)) {
int deleteIndex = sc.nextInt();
list.remove(deleteIndex);
}
numberOfQueries--;
}
sc.close();
list.forEach(a -> System.out.print(a +" "));
}
示例输入
5
12 0 1 78 12
2
Insert
5 23
Delete
0
预期输出
0 1 78 12 23
我的代码输出
12 0 1 78 12 23
【问题讨论】:
标签: java arrays string list java.util.scanner