我试图用用户输入的三个单词作为首字母缩略词:
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时,都会显示错误。例如,我试图输入三个单词&#34; One Two Three&#34;这就是结果:
请输入单词/短语: 一二三
线程中的异常&#34; main&#34; java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:13 at java.lang.String.charAt(String.java:646) at Acronym.main(Acronym.java:23)
答案 0 :(得分:2)
删除分号
for (x = 0; x < stringLength; x++);
^
正在终止for循环。对于终止if
语句
if (Character.isWhitespace(c));
^
请使用大括号围绕控制块