-1
我的任務是創建一個包含名字,姓氏,電話號碼和年齡的多維數組的程序。我目前得到的錯誤:添加,刪除和顯示方法
異常在線程「主要」 java.lang.Error的:未解決的問題,編譯: 輸入無法解決
at Lab2.<init>(Lab2.java:19)
at Lab2.main(Lab2.java:7)
** Editx2,我想我想通了。我最好喜歡用名字和姓氏來刪除聯繫人,但我無法弄清楚。我嘗試添加一個新的sysout來提示姓,就像我爲名字所做的那樣,然後添加另一個if語句,但最終卻做了一些簡單的事情。
import java.util.Scanner;
public class Lab2 {
static String[][] contacts = new String[10][4];
public static void main (String [] args) {
new Lab2();
}
public Lab2() {
String[][] contacts = new String[10][4];
Scanner input = new Scanner(System.in);
System.out.println("Welcome to my Contacts Directory. Enter a selection below: ");
while(true) {
System.out.println("1: Add a contact");
System.out.println("2: Remove a contact");
System.out.println("3: Display your contacts");
System.out.println("0: Exit the Contacts Directory");
int userChoice = input.nextInt();
switch(userChoice) {
case 1:
addContacts(contacts);
break;
case 2:
removeContacts(contacts);
break;
case 3:
displayContacts(contacts);
break;
case 0:
System.out.println("You are leaving the directory! Goodbye!");
System.exit(0);
}
}
}
private static void addContacts(String[][] contacts) {
Scanner input = new Scanner(System.in);
System.out.println("Enter First Name");
String fName = input.nextLine();
System.out.println("Enter Last Name");
String lName = input.nextLine();
System.out.println("Enter Phone Number");
String num = input.nextLine();
System.out.println("Enter Age");
String age = input.nextLine();
for (int i = 0; i < 10; i++) {
if (contacts[i][0] == null || contacts[i][0].equals(null)) {
contacts[i][0] = fName;
contacts[i][1] = lName;
contacts[i][2] = num;
contacts[i][3] = age;
boolean Inserted = true;
break;
}
}
}
private static void removeContacts(String[][] contacts) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the first name of the contact you want to remove: ");
String removeContact = input.nextLine();
if (removeContact != null) {
for (int i = 0; i < contacts.length; i++) {
for (int j = 0; j < contacts[i].length; j++) {
if (removeContact.equals(contacts[i][j])) {
contacts[i][0] = null;
contacts[i][1] = null;
contacts[i][2] = null;
contacts[i][3] = null;
break;
}
}
}
}
}
private static void displayContacts(String[][] contacts) {
for(int i = 0; i < contacts.length; i++) {
for(int j = 0; j < contacts[i].length; j++) {
System.out.println(contacts[i][j] + " ");
}
System.out.println();
}
}
}
這裏有類似的答案,但我無法從他們的代碼中找出它。它非常相似。 – JWags
removeContacts方法不起作用 – JWags
構造函數的作用是初始化實例變量,你的代碼中有很多不必要的東西。我建議你將while循環移出它。 –