如何在线程“主”中修复异常java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:0

时间:2019-06-19 15:11:37

标签: java

我正在制作温度转换器,遇到了以下问题:

您想再进行一次转换吗? (是/否)

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
    at java.lang.String.charAt(String.java:658)
    at Main.main(Main.java:79)
exit status 1

您可以在https://repl.it/@KyrillHuet/Temperature-Converter

处查看完整的代码

似乎第一部分工作正常,但最后一个异常导致了问题。

do{
  do{//New coversion?
    System.out.println();
    System.out.println("Would you like to make another conversion ? (Y/N)");

    response = sc.nextLine().charAt(0);
  } while (response != 'Y' & response != 'N'); // Filtering other awnsers than Y or N.

} while (response == 'Y');

我刚刚开始学习Java,在看书并检查完书后,一切似乎都还不错。 帮助将不胜感激。 =)

3 个答案:

答案 0 :(得分:0)

我敢肯定,在使用sc或sc.nextline之前,需要先对其进行空检查。这些复合命令链可能会给您带来麻烦,除非您确定它们不会为空。

答案 1 :(得分:0)

我已经尝试了您提供的链接中的代码。我不能说为什么它使用response = sc.nextLine().charAt(0);抛出该错误。但是,如果我使用response = sc.next().charAt(0);,就可以了。所以我的建议是您使用response = sc.next().charAt(0);。如果有人可以解释为什么会这样,那么他们可以自由地这样做。

答案 2 :(得分:-2)

代码中的小修正将起作用。由于光标已经在同一行中,所以下一行而不是下一行

do{
  do{//New coversion?
    System.out.println();
    System.out.println("Would you like to make another conversion ? (Y/N)");

    response = sc.next().charAt(0);
  } while (response != 'Y' & response != 'N'); // Filtering other awnsers than Y or N.

} whil

[已更新]

发布的原始问题的响应中包含nextLine。在尝试访问位置0处的Char时,将抛出超出范围的字符串索引。

这里的问题是next()和nextLine()之间的区别

next()读取空格之前的字符串。它在获得第一个空格后无法读取任何内容,并且nextLine()读取整行

在该示例中,由于使用了nextLine(),因此指针尝试在下一行不存在的零位置找到Char

因此将其保留为next()将在同一行中获取内容。