【发布时间】:2016-06-15 16:31:35
【问题描述】:
我在尝试删除或显示我创建的用户时不断收到错误消息。指向实际删除或显示某个用户的代码行。我似乎无法弄清楚错误来自哪里。
import java.util.*;
public class contactInfo {
public static void main(String[] args) {
String tracker[][] = {
{" ", " ", " ", " ",},
{" ", " ", " ", " ",},
{" ", " ", " ", " ",},
{" ", " ", " ", " ",},
{" ", " ", " ", " ",},
{" ", " ", " ", " ",},
{" ", " ", " ", " ",},
{" ", " ", " ", " ",},
{" ", " ", " ", " ",},
{" ", " ", " ", " ",}
};
Scanner input = new Scanner(System.in);
int picker = 0;
while (true) {
System.out.print("Please choose an option: \n 1. Add a user \n 2. Delete a user \n 3. Display a user \n 4. Quit ");
picker = input.nextInt();
if (picker == 1) {
addUser(tracker);
} else if (picker == 2) {
deleteUser(tracker);
} else if (picker == 3) {
displayUser(tracker);
} else {
break;
}
}
}
public static String[][] addUser(String[][] add) {
Scanner input = new Scanner(System.in);
System.out.print("Which user is this information for (1 - 10): ");
int user = input.nextInt();
System.out.println(" ");
System.out.print("Enter the users first name: ");
add[user][0] = input.next();
System.out.println(" ");
System.out.print("Enter the users last name: ");
add[user][1] = input.next();
System.out.println(" ");
System.out.print("Enter the users phone number (without dashes): ");
add[user][2] = input.next();
System.out.println(" ");
System.out.print("Enter the users age: ");
add[user][3] = input.next();
System.out.println(" ");
return add;
}
public static String[][] deleteUser(String[][] del) {
Scanner input = new Scanner(System.in);
System.out.print("Which user would you like to delete?: ");
int user = input.nextInt();
for (int i = 0; i < del.length - 1; i++) {
del[user][i] = " ";
}
return del;
}
public static String[][] displayUser(String[][] displ) {
Scanner input = new Scanner(System.in);
System.out.print("Which user would you like to display?: ");
int user = input.nextInt();
for (int i = 0; i < displ.length; i++) {
System.out.print(displ[user][i] + " ");
}
return displ;
}
}
【问题讨论】:
-
您的用户正在输入您的“用户”变量,您要求一个值 1-10 并将其用作数组的索引。数组在 Java 中是从零开始索引的。因此,要么从用户输入中减去 1,要么请求 0-9。此外,您应该检查收到的索引是否
-
顺便说一句,在删除和显示 for 循环中,不要使用 displ.length,而是使用 displ[user].length,因为这是您在循环内访问的内容!!!那是你的例外。但是请看我之前的评论,因为您还有其他错误。
-
感谢您的信息!我的课程中还没有涉及 ArrayList 类,但我会自己做一些研究。
标签: java arrays indexoutofboundsexception