2 回答
TA贡献1848条经验 获得超2个赞
我们可以使用 2 个不同的 ArrayList 来存储选项 1 和 2 中的用户名。然后在选项 3 中打印相同的 ArrayList。
List<String> vNames = new ArrayList();
List<String> bNames = new ArrayList();
if (choys == 1)
{
ch = new Scanner(System.in);
System.out.println("Enter name: ");
userBName = ch.nextLine();
System.out.println("Enter age: ");
userBAge = ch.nextInt();
if(userBAge >=18 && userBAge <=21)
{
System.out.println("Congrats "+userBName+"! Welcome to the team.");
bslot++;
bNames.add(userBName);
}
}
if (choys == 2)
{
ch = new Scanner(System.in);
System.out.println("Enter name: ");
userVName = ch.nextLine();
System.out.println("Enter age: ");
userVAge = ch.nextInt();
if(userVAge >=18 && userVAge <=21)
{
System.out.println("Congrats "+userVName+"! Welcome to the team.");
vSlot++;
vNames.add(userVName);
}
}
if (choys == 3)
{
System.out.println("Current number of recruits:\n");
System.out.println("Basketball team: ");
for(String name:bNames){
System.out.println("Username : "+ name);
}
}
TA贡献1858条经验 获得超8个赞
我曾尝试通过使用 while 循环让 vNames 和 bNames 留在 ArrayList 中来扩展@Shashank 的代码。
Scanner ch = new Scanner(System.in);
List<String> vNames = new ArrayList<String>();
List<String> bNames = new ArrayList<String>();
int choys;
int bslot = 0, vslot = 0;
Boolean run = true;
while (run) {
System.out.println("Enter Choice");
choys = Integer.parseInt(ch.next());
if (choys == 1) {
System.out.println("Enter name: ");
String userBName = ch.next();
System.out.println("Enter age: ");
int userBAge = Integer.parseInt(ch.next());
if (userBAge >= 18 && userBAge <= 21) {
System.out.println("Congrats " + userBName
+ "! Welcome to the team.");
bslot++;
bNames.add(userBName);
}
}else if (choys == 2) {
ch = new Scanner(System.in);
System.out.println("Enter name: ");
String userVName = ch.next();
System.out.println("Enter age: ");
int userVAge = Integer.parseInt(ch.next());
if (userVAge >= 18 && userVAge <= 21) {
System.out.println("Congrats " + userVName
+ "! Welcome to the team.");
vslot++;
vNames.add(userVName);
}
} else if (choys == 3) {
System.out.println("Current number of recruits:\n");
System.out.println("Basketball team: ");
for (String name : bNames) {
System.out.println("Username : " + name);
}
System.out.println("Volleyball team: ");
for (String name : vNames) {
System.out.println("Username : " + name);
}
} else {
run = false;
}
}
System.out.println("Program Ended");
添加回答
举报