gpt4 book ai didi

java - 显示 StringIndexOutOfBoundExceptions 错误

转载 作者:行者123 更新时间:2023-12-02 05:19:12 25 4
gpt4 key购买 nike

我正在尝试根据用户输入的三个单词创建首字母缩略词:

 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 时,就会显示错误。例如,我尝试输入三个单词“一二三”,结果如下:

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

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

最佳答案

删除分号

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

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

if (Character.isWhitespace(c));
^

请使用大括号括住控制 block

关于java - 显示 StringIndexOutOfBoundExceptions 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26640280/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com