【问题标题】:StringIndexOutOfBoundExceptions error is showing显示 StringIndexOutOfBoundExceptions 错误
【发布时间】:2014-10-29 20:41:35
【问题描述】:

我正在尝试从用户输入的三个单词中制作一个首字母缩略词:

 import java.util.Scanner;
 public class Acronym
 {
    public static void main(String[] args)
    {    

       Scanner input = new Scanner(System.in);
       String phrase;
       System.out.println("Please, enter the three words here>> ");
       phrase = input.nextLine();     
       char first, second, third;
       int stringLength;
       int x = 0;
       char c;
       stringLength = phrase.length();
       first = phrase.charAt(0);
       second = phrase.charAt(x + 1);
       third = phrase.charAt(x + 1);

          for( x = 0; x < stringLength; x++);
          {
             int a = 1;
             c = phrase.charAt(x);

             if(Character.isWhitespace(c));
               if( a <= 1)
                second = phrase.charAt(x+1);

             else if(a <= 2)
                third = phrase.charAt(x++);
          }

      System.out.println("The acronym is " + first + second + third);
   }

 }

但是,每当我尝试输入 StringIndexOutOfBoundExceptions 时,就会出现错误。例如我尝试输入三个单词“一二三”,结果如下:

请输入单词/短语: 一二三

线程“主”java.lang.StringIndexOutOfBoundsException 中的异常:字符串索引超出范围:13 在 java.lang.String.charAt(String.java:646) 在 Acronym.main(Acronym.java:23)

【问题讨论】:

  • 我已经通过删除循环后的分号解决了IndexOutOfBoundExceptions错误,谢谢!但是,结果是 OTn,这不是我想要的输出。因为我输入了“一二三”,所以我希望结果是“OTT”。我该怎么办?
  • 您的新问题是您只分配一次third,并且在循环之前的行。您已将其分配给初始 O 之后的角色。我不确定你对变量 a 的意图是什么,但是你将它分配给 1 并且你永远不会改变它。这意味着永远不会检查您的 else if 条件。我建议你离开电脑几分钟,然后在纸上勾勒出你想让你的程序做什么。

标签: java indexoutofboundsexception


【解决方案1】:

去掉分号

for (x = 0; x < stringLength; x++);
                                  ^

正在终止 for 循环。与终止 if 语句的分号相同

if (Character.isWhitespace(c));
                              ^

请用大括号包围控制块

【讨论】:

  • 但是,结果是 OTn,这不是我想要的输出。因为我输入了“一二三”,所以我希望结果是“OTT”。我该怎么办?
  • 您可以根据空格分割输入行,然后轻松输出每个结果字符串的第一个字母
  • 我邀请您尝试一下(提示:查看String.split)。如果您遇到困难,请回来,会有很多SO 用户愿意回答明智的问题! ;)
猜你喜欢
  • 2023-04-01
  • 2014-02-13
  • 2012-08-11
  • 2013-03-07
  • 2017-05-26
  • 2014-04-09
  • 2016-05-08
  • 2018-01-11
  • 1970-01-01
相关资源
最近更新 更多