java write。Action 2: adding a new user to the library. When the user of the software specifies action 2, your program must add a new user to the library. To add a new user, your program needs to ask the user three things: the role of user (an integer read using readPosInt: the integer 1 represents lender, the integer 2 represents borrower, any other integer must result in an error message "Unknown user role!" being printed and the software going immediately back to the main menu), the name of the user (a string read using readLine), and the initial number of books that the user lends (for a lender) or borrows (for a borrower). You program must then create the correct user, add it to the library, and print an information message. The program then goes back to the menu.
时间: 2023-11-22 15:55:09 浏览: 65
以下是Java代码实现:
```
import java.util.Scanner;
public class Library {
private User[] users;
private int numUsers;
public Library() {
users = new User[100];
numUsers = 0;
}
public void addUser() {
Scanner input = new Scanner(System.in);
System.out.print("Enter the role of user (1 for lender, 2 for borrower): ");
int role = readPosInt(input);
System.out.print("Enter the name of user: ");
String name = input.nextLine();
System.out.print("Enter the initial number of books: ");
int numBooks = readPosInt(input);
User user;
if (role == 1) {
user = new Lender(name, numBooks);
} else if (role == 2) {
user = new Borrower(name, numBooks);
} else {
System.out.println("Unknown user role!");
return;
}
users[numUsers++] = user;
System.out.println("User added successfully.");
}
private int readPosInt(Scanner input) {
int num;
while (true) {
try {
num = Integer.parseInt(input.nextLine());
if (num <= 0) {
throw new Exception();
}
break;
} catch (Exception e) {
System.out.print("Invalid input. Please enter a positive integer: ");
}
}
return num;
}
// other methods
}
class User {
private String name;
private int numBooks;
public User(String name, int numBooks) {
this.name = name;
this.numBooks = numBooks;
}
// getters and setters
}
class Lender extends User {
public Lender(String name, int numBooks) {
super(name, numBooks);
}
// other methods
}
class Borrower extends User {
public Borrower(String name, int numBooks) {
super(name, numBooks);
}
// other methods
}
```
在上述代码中,我们定义了一个类 `Library` 来表示图书馆,其中包括一个用户数组 `users` 和用户数量 `numUsers`。我们还定义了一个 `addUser()` 方法来添加新用户。在该方法中,我们首先使用 `readPosInt()` 方法读取用户角色、用户名和初始图书数量。然后根据用户角色创建正确的用户对象,并将其添加到用户数组中。最后,我们打印一条成功添加用户的消息。
在 `readPosInt()` 方法中,我们使用 `Scanner` 类的 `nextLine()` 方法读取用户输入,并使用 `Integer.parseInt()` 方法将其转换为整数。如果输入不是正整数,我们将提示用户重新输入,直到输入正确为止。
注意,在上述代码中,我们使用了继承来创建 `Lender` 和 `Borrower` 类,这两个类分别表示借款人和放款人。在实际应用中,您可以根据需要添加其他类来表示不同类型的用户。
阅读全文