Java 显示StringIndexOutOfBoundExceptions错误
我试图从用户输入的三个单词中提取首字母缩略词:Java 显示StringIndexOutOfBoundExceptions错误,java,indexoutofboundsexception,Java,Indexoutofboundsexception,我试图从用户输入的三个单词中提取首字母缩略词: 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
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);
}
}
import java.util.Scanner;
公共类首字母缩略词
{
公共静态void main(字符串[]args)
{
扫描仪输入=新扫描仪(System.in);
字符串短语;
System.out.println(“请在此处输入三个单词>>”;
短语=input.nextLine();
第一,第二,第三;
整数字符串长度;
int x=0;
字符c;
stringLength=短语.length();
第一个=短语.charAt(0);
第二个=短语.charAt(x+1);
第三个=短语.charAt(x+1);
对于(x=0;x
for (x = 0; x < stringLength; x++);
^
请用大括号包围控制块但是,结果是OTn,这不是我想要的输出。因为我输入了“一二三”,我希望结果是“OTT”。我该怎么办?你可以根据空格分割输入行,然后轻松输出每个结果字符串的第一个字母。我邀请你试试(提示:查看String.split
)。如果遇到问题,请回来,因为会有大量用户愿意回答合理的问题!;)我通过删除循环后的分号解决了IndexOutOfBoundExceptions错误,谢谢!但是,结果是OTn,这不是我想要的输出。因为我输入了“一二三”我希望结果是“OTT”。"我该怎么办?你的新问题是你只分配了third
一次,这是在循环之前的一行。你已经将它分配给了初始O
之后的字符。我不确定你对变量a
的意图是什么,但是你将它分配给1
,你永远不会更改它。这意味着如果
条件从未检查过,则您的。我建议您离开计算机几分钟,并在纸上勾画出您希望程序执行的操作。
if (Character.isWhitespace(c));
^