【问题标题】:Scanner nextLine() assigns empty value to a String [duplicate]扫描器 nextLine() 将空值分配给字符串
【发布时间】: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


【解决方案1】:

在使用5 23sc.nextInt() 阅读后没有超过换行符

文档https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine()nextLine()

将此扫描器前进到当前行并返回 被跳过了。

【讨论】:

    【解决方案2】:

    nextLine() 返回当前位置和下一行之间的文本。

    nextInt() 在刚刚读取的整数之后离开当前位置;这可能就在一行结束之前。

    因此,此时调用 nextLine() 会返回行尾和行尾之间的所有内容。也就是说,一个空字符串。

    要可靠地使用 Scanner,您必须时刻注意当前位置。

    【讨论】:

    • 返回行尾和行尾之间的所有内容。 - 这听起来有点令人困惑,尽管整个答案是正确的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-19
    • 2019-10-06
    • 1970-01-01
    • 2011-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多