簡體   English   中英

Java-超出范圍的字符串索引異常:11

[英]Java - String Index Out of Bounds Exception : 11

我正在編寫一個簡單的程序來獲取姓氏的名字的首字母。

input: Bruce Lee
output: L

這是代碼:

public char getFirstInitial()
    {
        char initial;
        int num = this.getFullName().length();

        while (this.getFullName().charAt(num) != ' ')  //this is line 120
        {
                num--;
        }
        initial = this.getFullName().charAt(num + 1);

        return initial;
    }


public String getFullName()
    {
        return fullName;
    }

我收到此錯誤:

java.lang.StringIndexOutOfBoundsException: String index out of range: 11
    at java.lang.String.charAt(Unknown Source)
    at lab1.Person.getFirstInitial(Person.java:120)

我不明白問題是什么。 謝謝

不要忘記索引從0開始。 所以第一個元素在索引0處,最后一個在長度-1處

如果指定的名稱無效,您還可以在該循環中檢查索引> = 0。

更改

int num = this.getFullName().length();

int num = this.getFullName().length() - 1;

索引從0開始,直到string.length()-1。

name.charAt(num)將拋出異常,bcoz索引將比全長減1。

更新代碼

while (name.charAt(num-1) != ' ')  //this is line 120
        {
                num--;
        }

在Java中,當您對字符串執行索引明智的操作時,總是會出現問題,因此首先應將stricng轉換為字符數組,然后再執行操作,如上文所述,如果您使用length()-1而不是length()那么數組越界錯誤將被刪除。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM