簡體   English   中英

為什么此for循環拋出IndexOutOfBoundsException?

[英]Why is this for loop throwing an IndexOutOfBoundsException?

請幫助,我在以下代碼中獲取索引超出范圍的異常

public static void main (String[] args){

    String st = "harpreet"; 

    for(int i=1; i<=st.length(); i++){

        System.out.print(st.charAt(i));

    }

}

數組偏移量從0開始,而不是1。如果從1開始,則會錯過偏移量0。此外,使compare <st.length(),否則將超出范圍。

for(int i=0; i< st.length(); i++){

更改您的代碼以讀取。

for(int i=0; i< st.length(); i++){

索引越界意味着您正在嘗試引用數組范圍中不存在的i。 由於數組是0到n-1而不是1到n,因此您將脫離數組。

數組索引以0開頭,但是您計算字符串的長度以1開頭,例如“ harpreet”的長度為8,而“ h”字母的索引為0。

IndexOutOfBoundException是運行時異常,當您嘗試訪問不存在的數組時發生。

您的代碼應為-

for(int i=0; i< st.length(); i++)

暫無
暫無

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

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