2D阵列&超出范围的例外

时间:2013-12-02 17:24:48

标签: java arrays multidimensional-array indexoutofboundsexception

我讨厌数组

所以我一直在做一些编码,我想出了一个我似乎无法解决的错误(超出范围的例外)。我相信我在说'array1 [counter2] [counter] = input2.nextLine();'是问题,但我不知道有什么问题!帮助,我不能忍受这些Out of Bounds异常

该计划的创意是一个在线电话簿,您可以添加联系人,查看他们,并按他们的名字,姓氏和电话号码进行搜索。

这是我正在使用的代码:

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

我知道它并不接近完成,但我是那种喜欢在继续之前解决所有问题的人,所以任何帮助都会受到赞赏! (:

2 个答案:

答案 0 :(得分:1)

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

由于ljgw表示数组索引从0开始,因此维度为3表示相应的索引为0,1和2.

答案 1 :(得分:0)

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