3 回答

TA貢獻1886條經驗 獲得超2個贊
問題是你在addDonor方法中創建變量索引。因此,每次調用該方法時,都會創建一個值為 0 的新變量,這就是它不會移動的原因。您應該在方法外部創建可變參數,并將其作為參數傳遞。
像這樣:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[] Name = new String[20];
String[] Mobile = new String[20];
char[] Blood_Gp = new char[20];
int[] Count_o_Donation = new int[20];
int[] Blood_Stock = new int[20];
int index = 0;
while (true){
displayMainMenu();
readAndVerify();
String choice = readAndVerify();
switch (choice){
case "1":
addDonor(Name, Mobile, Blood_Gp, Count_o_Donation, Blood_Stock, index);
index++
break;
}
if (choice.equals("e"))
break;
}
System.out.println(Name[0]);
System.out.println(Name[1]);
}
public static void addDonor(String[] a1, String[] a2, char[] a3, int[] a4, int [] a5), int index{
Scanner input = new Scanner(System.in);
System.out.print(" Enter the name (first and last):" + " ");
String name = input.nextLine();
System.out.print(" Enter Mobile No.:" + " ");
String phone = input.next();
if (phone.length() < 10 && phone.startsWith("0") == false){
while (true){
System.out.println("Wrong Mobile NO... try again!");
System.out.print(" Enter Mobile No.:" + " ");
phone = input.next();
if (phone.length() > 10 || phone.startsWith("0") == true)
break;
}
}
System.out.print(" Enter Blood Group Type (A, B or O):" + " ");
char blood = input.next().charAt(0);
while (blood != 'a' || blood != 'b' || blood != 'c'){
System.out.println("Wrong Blood Group Type... try again!");
System.out.println(" Enter Blood Group Type (A, B or O):" + " ");
blood = input.next().charAt(0);
if (blood == 'A' || blood == 'B' || blood == 'O')
break;
}
a1[index] = name;
a2[index] = phone;
a3[index] = blood;
a4[index] = 1;
a5[index] = 1;

TA貢獻1818條經驗 獲得超8個贊
這里有很多錯誤。
首先,您應該在課堂上真正收集所需的所有信息。這樣,您可以輕松地將其全部存儲在一個數組中。
public class donor{
String name;
String mobile
...
}
其次,因為你不知道你得到了多少輸入,數組真的是一種愚蠢的存儲方式。如果您使用列表,您可以簡單地執行以下操作:
List<Donor> donors = new ArrayList<>();
donors.add(donor);
如果需要使用數組,可以嘗試使用計數器。我可能會這樣做:
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String[] name = new String[20];
String[] mobile = new String[20];
char[] bloodGroup = new char[20];
int[] countODonation = new int[20];
int[] bloodStock = new int[20];
int counter = 0;
boolean continue = true;
while (continue){
displayMainMenu();
String choice = readAndVerify();
switch (choice){
case "1":
name[counter] = readName();
...
counter++;
break;
}
if (choice.equals("e"))
continue = false;
}
}
但是,再一次,您應該真正使用一個類來表示捐贈者的東西。還有一個列表。

TA貢獻1780條經驗 獲得超1個贊
這并不是一個真正的java問題,而是一個調試問題。您的計數器是其所在方法的本地計數器,因此每次調用該方法時,計數器都會重置。
變量具有作用域。變量的作用域取決于定義它的位置。在方法塊內部(或參數部分內部),變量將與方法塊一樣長。如果在類中定義為非靜態,則它將與實例一樣長。如果在類中定義為靜態,它將與類一樣長(大多數情況下這意味著永遠)
在你的情況下,你有2個選項:要么使變量靜態,要么在addDonor方法之外定義它,然后按值將其傳遞到addDonor方法中(因此你不能在addDonor內部增加它,無論你在哪里調用addDonor,都可以這樣做)。
如果使用靜態變量,則代碼保持不變。靜態變量通常在類的頂部定義。
如果將傳遞變量向下移動到 addDonor 中,則 main 方法將負責保留和遞增計數器變量。確保它僅在成功的迭代中遞增。
您還可以執行其他操作,但它們需要您了解對象。
添加回答
舉報