Devdit
 

Index 3 out of bounds for length 3 java คือ วิธีแก้ไข

1.3K

ฝึกเขียนภาษา Java สร้างตัวแปร array พร้อมกับใช้คำสั่ง for วนลูปข้อมูลทั้งหมดจากตัวแปร array ออกมา พอรันแล้วข้อมูลแสดงแต่มี Error แจ้งว่า Exception in thread "main" java lang ArrayIndexOut Of BoundsException: Index 3 out of bounds for length 3 ปัญหานี้ต้องแก้ไขอย่างไร โค้ดบางส่วนตามด้านล่าง

class Main {  
  public static void main(String args[]) { 
    String colors[] = {"red", "green", "blue"};
    for( int i=0; i<=colors.length; i++ ) {
      System.out.println( colors[i] );
    }
  } 
}

 

วิธีแก้ไข

ปัญหานี้เกิดจากมีการเข้าถึงข้อมูลที่เกินขอบเขต หรือขนาดของตัวแปร array ที่กำหนดไว้ โดยโค้ดส่วนที่ทำให้เกิด Error คือเงื่อนไขในคำสั่ง for loop ตรง i<=colors.length สามารถแก้ไขโค้ดได้ดังนี้

class Main {  
  public static void main(String args[]) { 
    String colors[] = {"red", "green", "blue"};
    for( int i=0; i<colors.length; i++ ) {
      System.out.println( colors[i] );
    }
  } 
}

ผลลัพธ์

red
green
blue
เขียน 1 ปีที่แล้ว
ชอบ
ลิ้งก์
แชร์
Devdit มีช่อง YouTube แล้ว
เราสร้างวิดีโอเกี่ยวกับเทคโนโลยี ทำตามง่ายๆ