【问题标题】:Error at System.out.print(word.charAt(count))System.out.print 出错(word.charAt(count))
【发布时间】:2015-10-30 00:33:40
【问题描述】:

我正在尝试获取用户输入并从最后一个字符开始打印单词,并将前一个字符添加到下一行,前面少一个空格,看起来它向右对齐。

但它显示有错误: System.out.print(word.charAt(count));

Scanner input = new Scanner(System.in);
System.out.print("Enter word to print: ");
String word = input.nextLine();
System.out.println();

int line, space, count = -1;

for (line = word.length(); line > 0; line--){

  for (space = line; space > 0; space--){
    System.out.print(" ");
    count++;
    }

  for ( ; count <= word.length(); count++){
    System.out.print(word.charAt(count));
  }

System.out.println();
}

错误显示为:

Exception in thread "main java.lang.String.IndexOutOfBoundsException: S
at java.lang.String.charAt(String.java:658)
at HelloWorld.main(HelloWorld.java:22)

【问题讨论】:

  • 请说明您收到的错误。请告诉我们您在研究此错误时发现了什么。
  • 但它显示有错误”请告诉我们这是什么,而不是让我们猜测。
  • 您有一个IndexOutOfBoundsException 原因是您尝试从String 获取超出当前长度的字符,记住,String 是零索引

标签: java charat


【解决方案1】:

问题出在您的最后一个 for 循环中。 count &lt;= word.length() 表示只要count 不超过word.length(),循环就会继续运行,这是一个问题,因为String 中每个字符的索引以0 开头,而不是1。

因此,例如,如果您输入一个五个字母的单词,for 循环将一直运行,直到 count 等于 5。在其最后一次迭代中,当 count 等于 5 时,它会抛出一个 @987654329 @ 因为word 只上升到索引4(第一个字符在0,第二个在1,依此类推,这意味着第五个字符在索引4)。

因此,for 循环的退出条件应该是 count &lt;= word.length(),而不是 count &lt; word.length()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-19
    • 1970-01-01
    • 1970-01-01
    • 2018-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    相关资源
    最近更新 更多