【问题标题】:2D Array's & Out of bounds exceptions二维数组和越界异常
【发布时间】:2013-12-02 17:24:47
【问题描述】:

我讨厌数组

所以我一直在进行一些编码,但我遇到了一个我似乎无法修复的错误(超出范围异常)。我相信我在说'array1[counter2][counter] = input2.nextLine();'是问题,但我不知道出了什么问题!求助,我受不了这些越界异常

该程序的理念是一个在线电话簿,您可以在其中添加联系人、查看他们并通过他们的名字、姓氏和电话号码进行搜索。

这是我正在使用的代码:

import java.util.Scanner; 
import java.awt.*;
public class testMattWalker {
 //
 public static void main (String[] args){
   //Declare all your variables here. Make sure to provide a comment explaining the purpose of each variable
   Scanner input = new Scanner(System.in);
   Scanner input2 = new Scanner(System.in);
   Scanner input3 = new Scanner(System.in);
   Scanner input4 = new Scanner(System.in);
   int counter = 0;
   int counter2 = 0;
   boolean go = true;

   //Temp VAriables for entry 
   String firstNameOfEntry = "";
   String lastNameOfEntry = "";
   String personPhoneNumber = "";
   //

   //create array
   String [][] array1 = new String[5][3];

   while (go) {

   String choice = "";

   System.err.println("\n\n\n\n\n\n\n\n\nDIDGITAL PHONE BOOK 2013");   
   System.out.println("1- Create phone book\n2- Display phone book\n3- Find person(s) by last name\n4- Find person(s) by first name\n5- Find person(s) by phone number\n6- Exit application");
   choice = input.nextLine(); 

   if (choice.equals("1") && counter2 != 6) {

     System.err.println("\n\n\n\n\nPHONE BOOK ENTRY CREATOR:");
     System.out.println("Please enter the first name of the person you wish to enter: ");
     array1[counter2][counter] = input2.nextLine();
     counter++;

     System.out.println("Please enter the last name of the person you wish to enter: ");
     array1[counter2][counter] = input3.nextLine();
     counter++;

     System.out.println("Please enter the phone number of this person: example:9057773344");
     array1[counter2][counter] = input4.nextLine();
     counter++;
     counter2++;

   }else if (choice.equals("2")) {



   }else if (choice.equals("3")) {



   }else if (choice.equals("4")) {



   }else if (choice.equals("5")) {



   }else if (choice.equals("6")) {

   }
   }
 }// end of main
}// end of class

我知道这还没有完成,但我是那种喜欢在继续之前解决所有问题的人,所以任何帮助都将不胜感激! (:

【问题讨论】:

    标签: java arrays multidimensional-array indexoutofboundsexception


    【解决方案1】:

    您将数组的第二维设置为 3,但在您的代码中,您将 1 加到 counter 3 次,这意味着它在代码的第一次迭代后超出了数组的范围。

    由于 ljgw 表示数组索引从 0 开始,所以维度为 3 表示对应的索引为 0,1 和 2。

    【讨论】:

      【解决方案2】:

      请记住,数组索引以 0 开头。所以:5 已经超出 counter2 的范围。

      【讨论】:

        猜你喜欢
        • 2019-11-02
        • 2013-05-01
        • 1970-01-01
        • 2014-02-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-04
        • 1970-01-01
        相关资源
        最近更新 更多