由于您需要为 4 个用户循环(根据您的评论),因此您应该围绕整个输入过程进行循环:
for (int i = 0; i < 4; i++) {
// read the input
// add name to correct array
}
您应该为每种事件类型保留计数器:
// here come all your variable declarations
// declare the counters
int hockeyCounter = 0;
int tinaCounter = 0;
int catsCounter = 0;
int startrekCounter = 0;
// no need to redeclare the keyboard all the time, just once is enough
Scanner keyboard = new Scanner(System.in);
for (int i = 0; i < 4; i++) {
System.out.println("Which Event would you like to purchase a ticket for?");
System.out.println("1. Hockey Game 2. Tina Turner Concert \n"
+ "3. Cats Play 4. Star Trek Convention");
int input = keyboard.nextInt();
System.out.println("Please enter your first and last name");
String name = scan.nextLine();
switch (input) {
case 1: Hockey_Game[hockeyCounter++] = name; break;
case 2: Turner_Concert[tinaCounter++] = name; break;
case 3: Cats_Play[catsCounter++] = name; break;
case 4: StarTrek_Convention[startrekCounter++] = name; break;
default: System.out.println(input + " is not a valid input");
}
}
现在完美了吗?不,不完全是。还是有一些问题:
- 我没有考虑可用门票的最大数量。如果所有客户都想要一张猫游戏的门票,此代码将崩溃。
- 有很多代码重复。忽略前面提到的问题已经让我很恼火了。
- 变量名应始终以小写字母开头(最好使用 camelCase)。这是一个 Java 约定,可以帮助其他人阅读您的代码。
以某种方式一次解决所有这些问题会更好。为此,我将提出一个数组数组(虽然这对于初学者来说可能更复杂,但会使代码更简单):
final int EVENT_COUNT = 4;
final String[] EVENTS = { "Hockey Game", "Tina Turner Concert",
"Cats Play", "Star Trek Convention" };
final int[] LIMITS = { 10, 5, 3, 3 };
String[][] buyers = new String[EVENT_COUNT][];
int[] counters = new int[EVENT_COUNT];
for (int i = 0; i < EVENT_COUNT; i++) {
buyers[i] = new String[LIMITS[i]];
}
final int CUSTOMER_COUNT = 4;
Scanner keyboard = new Scanner(System.in);
for (int i = 0; i < CUSTOMER_COUNT; i++) {
System.out.println("Which Event would you like to purchase a ticket for?");
for (int j = 0; j < EVENT_COUNT; j++) {
System.out.print((j+1) + ". " + EVENTS[j] + " ");
}
System.out.println();
int input = keyboard.nextInt();
if (input < 1 || input > EVENT_COUNT) {
System.out.println(input + " is not a valid choice");
i--;
} else if (counters[input-1] >= LIMITS[input-1]) {
System.out.println(EVENTS[input-1] + " is sold out!");
i--;
} else {
System.out.println("Please enter your first and last name");
buyers[input-1][counters[input-1]++] = scan.nextLine();
}
}