import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int num = 3; // 假设要输入3个人的信息 String[] names = new String[num]; int[] ages = new int[num]; String[] genders = new String[num]; for (int i = 0; i < num; i++) { System.out.println("请输入第" + (i + 1) + "个人的姓名:"); names[i] = scanner.nextLine(); System.out.println("请输入第" + (i + 1) + "个人的年龄:"); ages[i] = scanner.nextInt(); scanner.nextLine(); // 必须加上这一行,否则会导致输入性别时出错 System.out.println("请输入第" + (i + 1) + "个人的性别:"); genders[i] = scanner.nextLine(); } for (int i = 0; i < num; i++) { System.out.println("第" + (i + 1) + "个人的信息:"); System.out.println("姓名:" + names[i]); System.out.println("年龄:" + ages[i]); System.out.println("性别:" + genders[i]); } } }这段代码如何与list连用
时间: 2024-01-24 22:05:44 浏览: 64
java代码-实训4-3 import java.util.Scanner
可以使用List来存储输入的人员信息,可以定义一个Person类来表示每一个人的信息,然后将每个Person对象添加到List中。修改后的代码如下:
```java
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num = 3; // 假设要输入3个人的信息
List<Person> personList = new ArrayList<>();
for (int i = 0; i < num; i++) {
System.out.println("请输入第" + (i + 1) + "个人的姓名:");
String name = scanner.nextLine();
System.out.println("请输入第" + (i + 1) + "个人的年龄:");
int age = scanner.nextInt();
scanner.nextLine();
System.out.println("请输入第" + (i + 1) + "个人的性别:");
String gender = scanner.nextLine();
Person person = new Person(name, age, gender);
personList.add(person);
}
for (int i = 0; i < num; i++) {
System.out.println("第" + (i + 1) + "个人的信息:");
System.out.println("姓名:" + personList.get(i).getName());
System.out.println("年龄:" + personList.get(i).getAge());
System.out.println("性别:" + personList.get(i).getGender());
}
}
}
class Person {
private String name;
private int age;
private String gender;
public Person(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getGender() {
return gender;
}
}
```
这样就可以通过List来存储每个人的信息,方便后续的操作。
阅读全文