这段代码中的 indexOf 有什么问题?为什么我尝试打印 indexOf answer1 时得到 -1?

what's wrong with indexOf in this code? why I get -1 when I try to print indexOf answer1?

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

您所有的电台名称都有 spaces。

s.next() 将从 Scanner 中读取下一个标记,其中不会有 space。

改用s.nextLine()


作为调试此类问题的一般提示,请尝试在调试器中查看 answer1answer2 的值(或者甚至只是将它们打印出来)。那么不匹配的原因就很明显了。

验证您在终端中写入的站名。因为当 idexOf 没有找到单词时返回 -1 值。打印写入终端的站点名称并分析 answer1 变量和 answer2

中可能添加的空格或回车