I have a Java program with a model class utilizing getters/setters that build objects that are stored in an ArrayList. In these objects are a firstName, lastName, address, and PIN.
This is the code in the model class, followed by the code in another class for building these objects:
model class:
public class AccountCreator {
// variables
private String firstName;
private String lastName;
private String address;
private int PIN = 0;
private double balance = 0;
// giving object sane name
@Override
public String toString() {
return firstName + " " + lastName;
}
// set
public void setFirstName(String first) {
firstName = first;
}
public void setLastName(String last) {
lastName = last;
}
public void setAddress(String addr) {
address = addr;
}
public int setPIN() {
PIN = (int) (Math.random() * 9000) + 1000;
return PIN;
}
// get
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getAddress() {
return address;
}
public int getPIN() {
return PIN;
}
}
Code for adding objects to list:
private ArrayList<AccountCreator> accountList = new ArrayList<>();
Scanner accScan = new Scanner(System.in);
AccountCreator account = new AccountCreator();
System.out.println("Please enter the following account details: ");
System.out.println("First name: ");
account.setFirstName(accScan.nextLine());
System.out.println("Last name: ");
account.setLastName(accScan.nextLine());
System.out.println("Full address: ");
account.setAddress(accScan.nextLine());
account.setPIN();
System.out.println("New account PIN is: " + account.getPIN());
As you can see, I use Scanner to get input for all the object details, and I use .nextLine() so I can catch full addresses and multiple surnames.
Later, I have code which looks into the ArrayList and edits the details of already stored objects. This is that code:
int c = accScan.nextInt();
for (int d = 0; d < accountList.size(); d++) {
if (c == d) {
System.out.println(accountList.get(c));
System.out.println("First name: " + accountList.get(c).getFirstName());
System.out.println("Last name: " + accountList.get(c).getLastName());
System.out.println("Full address: " + accountList.get(c).getAddress());
System.out.println("PIN number: " + accountList.get(c).getPIN());
TextSpacer();
}
}
The issue is that when I try to edit the stored objects, the program does not correctly wait for my input and the object's data becomes a mess. This doesn't happen if I only use .next(), but that is not a solution. I don't understand why nextLine() works when creating the object, but not edit it.
Edit: After following this answer by Rohit Jain, I placed accScan.nextLine();
after the line int m = accScan.nextInt();
in my code, which has addressed the issue.