【问题标题】:what's wrong with indexOf in this code? why I get -1 when I try to print indexOf answer1?这段代码中的 indexOf 有什么问题?为什么我在尝试打印 indexOf answer1 时得到 -1?
【发布时间】:2018-12-14 11:09:24
【问题描述】:
public static void main(String[] args) {
    // write your code here
        ArrayList<String>line1=new ArrayList<String>();
        line1.add("el marg");
        line1.add("ezbt el nakhl");
        line1.add("ain shams");
        line1.add("el matria");
        line1.add("el helmia");
        Scanner s=new Scanner(System.in);
        System.out.println("Entry Station");
        String answer1=s.next();
        Scanner a=new Scanner(System.in);
        System.out.println("Exit Station");
        String answer2=a.next();

        System.out.println(line1.subList(line1.indexOf(answer1),line1.indexOf(answer2)));
    }
}

我想打印一个火车站的子列表,它在入口站和出口站之间,但有些错误,即使用户在数组列表中键入了一个车站,它也会给我 -1

【问题讨论】:

  • 请注意,您不需要多个 Scanner 实例。

标签: java arraylist indexof


【解决方案1】:

您所有的电台名称都有空格。

s.next() 将从Scanner 中读取下一个标记,其中没有空格。

请改用s.nextLine()


作为调试此类问题的一般提示,请尝试在调试器中查看answer1answer2 的值(或者甚至将它们打印出来)。然后应该很明显为什么它不匹配。

【讨论】:

    【解决方案2】:

    验证您在终端中写入的站名。因为 idexOf 没有找到单词时返回 -1 值。打印写终端的站名并分析可能在 answer1 变量和 answer2 中添加的空格或 Enter

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-25
      • 2017-06-04
      • 1970-01-01
      • 2016-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多