为什么nextLine()不一直在我的Java程序中等待输入?

时间:2019-01-08 12:03:21

标签: java input java.util.scanner getter-setter

我有一个带有模型类的Java程序,该类使用利用getter / setter来构建存储在ArrayList中的对象。在这些对象中,包括firstName,lastName,地址和PIN。

这是模型类中的代码,然后是另一个类中用于构建这些对象的代码:

模型类:

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;
}
}

将对象添加到列表的代码:

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());

如您所见,我使用Scanner获取所有对象详细信息的输入,并且使用.nextLine()以便捕获完整的地址和多个姓氏。

稍后,我有代码可以查询ArrayList并编辑已存储对象的详细信息。这是该代码:

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();
  }
 }

问题是,当我尝试编辑存储的对象时,程序无法正确等待我的输入,并且对象的数据变得一团糟。如果仅使用.next(),则不会发生这种情况,但这不是解决方案。我不明白为什么在创建对象时nextLine()可以工作,但不能对其进行编辑。

编辑:在遵循this answer by Rohit Jain之后,我在代码中的accScan.nextLine();行之后放置了int m = accScan.nextInt();,此问题已得到解决。

0 个答案:

没有答案