Java 由于错误创建IndexOutOfBoundsException而导致编译错误

Java 由于错误创建IndexOutOfBoundsException而导致编译错误,java,indexoutofboundsexception,throw,Java,Indexoutofboundsexception,Throw,我编写了一个代码来显示公告牌程序,我想在用户输入无效选项时使用IndexOutOfBoundsException来防止系统崩溃。我似乎无法让它正常运行 以下是我所拥有的: if (index <= messages.size()) this.text = messages.get(index - 1); else throw new IndexOutOfBoundsException("Invalid Number Choice"); if(index很好,您正在使用S

我编写了一个代码来显示公告牌程序,我想在用户输入无效选项时使用
IndexOutOfBoundsException
来防止系统崩溃。我似乎无法让它正常运行

以下是我所拥有的:

if (index <= messages.size())
    this.text = messages.get(index - 1);
else
    throw new IndexOutOfBoundsException("Invalid Number Choice"); 

if(index很好,您正在使用StringIndexOutOfBoundsException


但是,根据您的错误“类java.util.IndexOutOfBoundsException中的不可编译源代码-构造函数IndexOutOfBoundsException”我应该提到这一点您必须导入了另一个异常类,它应该是java.lang.IndexOutOfBoundsException

请提供您的代码。有这样的构造函数,但异常表明您有
java.util.IndexOutOfBoundsException
。您不能将索引与ArrayList绑定在一起,因为您有消息.size()在您的代码中,也许可以尝试在代码中使用大括号。@Eran异常类是
java.lang.IndexOutOfBoundsException
。我们不知道
java.util.IndexOutOfBoundsException
,它似乎是OP创建的自定义类,将失败,因为您无法在项目中创建
java.
包。不要修改索引,因为它会让人困惑,但您也会得到
index=0;
IndexOutOfBoundsException
。请改用
if(index
N.B.less而不是less或equal。您还应该检查索引是否为非负以确保正确。我解决了它。我将其更改为try..catch.public void setText(int index)抛出StringIndexOutOfBoundsException;{try{(index