以下是我的问题: “创建一个程序来跟踪用户输入的以下信息: 名字、姓氏、电话号码、年龄 现在 - 让我们将其存储在一个多维数组中,该数组将容纳 10 个这样的联系人。所以我们的多维数组需要 10 行 4 列。 您应该能够添加、显示和删除阵列中的联系人。 ” **FixedThis(我被困在创建一个方法来回调并将用户输入输入到我的二维数组中。)
**新问题,我收到第 3 种情况的错误,我似乎无法返回打印显示的方法,有什么建议可以解决此问题吗?
导入java.util.Scanner; 公开课Lab2 { String[][] myArray = new String[10][4];
public static void main(String[]args)
{
new Lab2();
}
public Lab2()
{
Scanner input = new Scanner(System.in);
while(true)
{
System.out.println("Welcome to the Contact Directory, please select from following: ");
System.out.println("Type 1 to add contact, 2 to remove contact, 3 to display contacts and 0 to exit.");
int intChoice = input.nextInt();
input.nextLine();
String strFirstName;
String strLastName;
switch(intChoice)
{
case 1:
System.out.println("Enter First Name");
strFirstName = input.nextLine();
System.out.println("Enter Last Name");
strLastName = input.nextLine();
System.out.println("Enter Phone Number");
String strPhoneNumber = input.nextLine();
System.out.println("Enter Age");
String strAge = input.nextLine();
addItem(strFirstName, strLastName, strPhoneNumber, strAge);
break;
case 2:
System.out.println("Enter First Name to Remove");
strFirstName = input.nextLine();
System.out.println("Enter Last Name to Remove");
strLastName = input.nextLine();
removeItem(strFirstName, strLastName);
break;
case3:// GETTING AN ERROR UNREACHABLE STATEMENT
displayItems();
break;
case 0:
System.exit(0);
}
}
}
public void addItem(String strFirstName, String strLastName,
String strPhoneNumber, String strAge)
{
for(int i = 0; i < myArray.length; i++)
{
for(int j = 0; j < myArray[i].length; j++)
{
if (myArray[i][0] == null)
{
myArray[i][0] = strFirstName;
myArray[i][1] = strLastName;
myArray[i][2] = strPhoneNumber;
myArray[i][3] = strAge;
; break;
}
}
}
}
public void removeItem(String strFirstName, String strLastName)
{
int i, j;
for(i = 0; i < myArray.length; i++)
{
for(j = 0; j < myArray.length - 1; j++){
myArray[i][j] = myArray[i + 1][j];
break;
}
}
}
public void displayItems()
{
for(int i = 0; i < myArray.length; i++)
{
for (int j = 0; j < myArray[i].length; j++)
{
System.out.print(myArray[i][j] + " ");
}
System.out.println();
}
}
}
最佳答案
您得到的提示应该是用于解决您的问题的代码。找到下一个可用的并添加它。
if (myArray[i][0] == null)
{
myArray[i][0] = strFirstName;
myArray[i][1] = strLastName;
myArray[i][2] = strPhoneNumber;
myArray[i][3] = strAge;
blnInserted = true;
break;
}
您不需要第二个循环,因为您只是根据第一个名称检查整个条目是否为 null
。在删除封闭的第二个循环后,应将代码添加到您感到困惑的部分中。
此外,不需要在 ||
之后进行 null
检查。如果为 null
,您将无法检查相等性,因为这样做需要一个不能为 null
的实例。
关于java - 使用Java方法添加用户元素多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37997297/