当我的其他人应该阻止它时,为什么我会得到IndexOutOfBoundsException?

ham*_*314 0 scala exception playframework

我正在进行某种测验,并有一个问题和答案列表,通过控制器转移到我的视图类.人们可以在一个页面上提问和回答问题,然后我的系统会"收集"这些问题以便从中进行测验.

如果您是第一个启动程序/测验的人,则问题列表为空.因此,我想检查一个带有if/else子句的空测验,if-case似乎工作正常,但是else-case抛出一个IndexOutOfBoundsException而我不明白为什么.我认为当问题列表为空时不会使用else-part,因此不应该抛出异常.应该....

查看课程:

@(questionList: List[Question], answerList: List[Answer], answerRadioForm: Form[Answer])

@if(questionList.length == 0){
    No questions yet!
}

else {
<!-- As only the highest ranked question gets put into the List, there is only one entry on first place -->
<b>@questionList.get(0).questionText</b>

    @for(question <- questionList)  {
        @question.questionText - @question.ownerID <br>
    }
} 
Run Code Online (Sandbox Code Playgroud)

错误:

[IndexOutOfBoundsException: Index: 0, Size: 0]
49          <b>"""),_display_(/*27.8*/questionList/*27.20*/.get(0).questionText),format.raw/*27.40*/("""</b>
Run Code Online (Sandbox Code Playgroud)

那么,我在这里错过了什么?

ham*_*314 5

我找到了一个解决方案,尽管回答你自己的问题是不好的做法,我已经搜索了几个小时,也许我的回答可以帮助其他人:

if/else之间不能有返回/换行符.

难道工作:

@if(questionList.length == 0){
    No questions yet!
}

else { ...
Run Code Online (Sandbox Code Playgroud)

作品:

@if(questionList.length == 0){
    No questions yet!
} else {
Run Code Online (Sandbox Code Playgroud)

编辑:同样@if(questionList.length > 0){工作,对于意外插入换行符是稳定的,并且更容易阅读和理解,我将使用它而不是其他.

  • 回答你自己的问题并不是一个坏习惯.http://stackoverflow.com/help/self-answer (5认同)