我想要一个将有关人员详细信息存储在arraylist中的程序。我想提示用户输入并将每个结果存储在arraylist中。我该怎么做呢?以及之后如何查看存储在arraylist中的所有内容? 它不需要反映我的代码,只是似乎无法弄清楚我是如何使用setter和getter的类,然后创建一个新的主类来提示用户输入并将该输入存储在arraylist中。 >
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class salesPersonMain {
public static void main(String[] args) throws InputValidationException {
Scanner input = new Scanner(System.in);
//ask user for input and get input
System.out.println("Enter id: ");
int id = Integer.parseInt(input.nextLine());
System.out.println("Enter first name:");
String firstName = input.nextLine();
System.out.println("Enter last name:");
String lastName = input.nextLine();
//save in array list
List<salesPerson> sPerson = new ArrayList<salesPerson>();
sPerson.add(new salesPerson(id, firstName, lastName));
}
}
I have another class for the salesperson:
import java.util.ArrayList;
public class salesPerson<sPerson> {
//create variables for sales person
private int id;
private String firstName;
private String lastName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) throws InputValidationException {
if (firstName.matches("\\p{Upper}(\\p{Lower}){2,20}")) {
} else {
throw new InputValidationException();
}
{
this.firstName = firstName;
}
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName)throws InputValidationException {
if (lastName.matches("\\p{Upper}(\\p{Lower}){2,20}")) {
} else {
throw new InputValidationException();
}
{
this.lastName = lastName;
}
}
//creates array of salespeople
private ArrayList<sPerson> salesPerson;
public salesPerson() {
salesPerson = new ArrayList<>();
}
//adds new salesperson to the array
public void add(salesPerson sPerson) {
salesPerson.add((sPerson) sPerson);
}
答案 0 :(得分:1)
您需要循环才能重复获取输入:
public static void main(String[] args) throws InputValidationException {
Scanner input = new Scanner(System.in);
List<salesPerson> sPerson = new ArrayList<salesPerson>();
// Loop forever
// Need a way to break the loop. One option: have the user
// input "q" for quit
while (true) {
//ask user for input and get input
System.out.println("Enter id ('q' to quit): ");
String temp = input.nextLine();
if (temp.equals("q")) break;
int id = Integer.parseInt(temp);
// This should be in try/catch in case parseInt fails
System.out.println("Enter first name:");
String firstName = input.nextLine();
System.out.println("Enter last name:");
String lastName = input.nextLine();
//save in array list
sPerson.add(new salesPerson(id, firstName, lastName));
}
// Print the list
sPerson.forEach(System.out::println);
}
因此它可以正确打印出来,您需要覆盖toString
类中的salesPerson
函数:
public class salesPerson {
// Other code here.....
@Override
public String toString() {
return id + "," + firstName + " " + lastName;
}
}