Java 什么';这段代码中的indexOf有什么问题吗?为什么我在打印答案索引1时得到-1? publicstaticvoidmain(字符串[]args){ //在这里编写代码 ArrayListline1=新的ArrayList(); 第1行添加(“el marg”); 第1行添加(“ezbt el-nakhl”); 第1行添加(“ain shams”); 第1行添加(“el matria”); 第1行添加(“el helmia”); 扫描仪s=新的扫描仪(System.in); System.out.println(“入口站”); 字符串answer1=s.next(); 扫描仪a=新的扫描仪(System.in); System.out.println(“出口站”); 字符串answer2=a.next(); System.out.println(第1行子列表(第1行indexOf(answer1),第1行indexOf(answer2)); } }
我想打印一个在进站和出站之间的火车站的子列表,但有点错误,它给了我-1,即使用户在arraylist中键入了一个站您所有的站名都有空格Java 什么';这段代码中的indexOf有什么问题吗?为什么我在打印答案索引1时得到-1? publicstaticvoidmain(字符串[]args){ //在这里编写代码 ArrayListline1=新的ArrayList(); 第1行添加(“el marg”); 第1行添加(“ezbt el-nakhl”); 第1行添加(“ain shams”); 第1行添加(“el matria”); 第1行添加(“el helmia”); 扫描仪s=新的扫描仪(System.in); System.out.println(“入口站”); 字符串answer1=s.next(); 扫描仪a=新的扫描仪(System.in); System.out.println(“出口站”); 字符串answer2=a.next(); System.out.println(第1行子列表(第1行indexOf(answer1),第1行indexOf(answer2)); } },java,arraylist,indexof,Java,Arraylist,Indexof,我想打印一个在进站和出站之间的火车站的子列表,但有点错误,它给了我-1,即使用户在arraylist中键入了一个站您所有的站名都有空格 s.next()将从扫描器中读取下一个令牌,扫描器中没有空格 改用s.nextLine() 作为调试此类问题的一般提示,请尝试在调试器中查看answer1和answer2的值(甚至打印出来)。然后应该非常清楚为什么不匹配。验证您在终端中写入的站点名称。因为当idexOf找不到单词时返回-1值。打印写入终端的站名,并分析可能添加到answer1变量和answer
s.next()
将从扫描器中读取下一个令牌,扫描器中没有空格
改用s.nextLine()
作为调试此类问题的一般提示,请尝试在调试器中查看answer1
和answer2
的值(甚至打印出来)。然后应该非常清楚为什么不匹配。验证您在终端中写入的站点名称。因为当idexOf找不到单词时返回-1值。打印写入终端的站名,并分析可能添加到answer1变量和answer2中的空格或输入。请注意,您不需要多个扫描仪实例。
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)));
}
}