【发布时间】: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