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
最佳答案
您的所有电台名称都有空格。
s.next()
将从 Scanner
读取下一个 token ,其中不会有空格。
改用s.nextLine()
。
作为调试此类问题的一般技巧,请尝试在调试器中查看 answer1
和 answer2
的值(甚至只是打印出来)。那么不匹配的原因应该是非常明显的。
关于java - 这段代码中的indexOf 有什么问题?为什么当我尝试打印indexOfanswer1时得到-1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53778605/