gpt4 book ai didi

java - 二维数组和越界异常

转载 作者:行者123 更新时间:2023-12-01 13:46:28 24 4
gpt4 key购买 nike

我讨厌数组

所以我一直在做一些编码,但我发现了一个错误(越界异常),我似乎无法修复它。我相信我所说的“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

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

最佳答案

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

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

关于java - 二维数组和越界异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20334185/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com