我遇到一些代码问题。当我尝试使用“退出”打破我的循环时它不会停止。如果我开始键入quit,它会按预期中断,但第二次循环运行并且我键入退出它没有破坏。有什么问题?
public static void interactionLoop() {
input = new Scanner(System.in);
String ssn = null;
String message = null;
int accountNr;
double amount;
while(true) {
for(Customers aCustomer : Customers.getCustomerList()) {
System.out.println(aCustomer.getName() + ", " + aCustomer.getSsn());
}
System.out.println("Choose a customer by using SSN.");
System.out.print(">> ");
ssn = input.nextLine();
if(ssn.equals("quit")) {
break;
}
Customers theChosenCustomer = Customers.getCustomerBasedOnSSN(ssn);
ArrayList<Accounts> accList = theChosenCustomer.getAccountList();
for(Accounts anAccount : accList) {
if(anAccount instanceof Savings) {
System.out.print("(Savings, " + anAccount.getAccountNr() + ")" + "\n");
}
if(anAccount instanceof Loans) {
System.out.print("(Loans, " + anAccount.getAccountNr() + ")" + "\n");
}
}
System.out.print("Enter the account that you want to work with using the account number:\n>> ");
accountNr = input.nextInt();
Accounts chosenAccount = theChosenCustomer.getSpecificAccount(accountNr);
System.out.println("Account balance: "+chosenAccount.getBalance());
for(Transaction t : chosenAccount.getTransaction()) {
System.out.println(t.getDateAndTime().getTime() +", " + t.getComment() +": " + t.getAmount());
}
System.out.println("\n");
System.out.print("Please enter the amount of money you wish you withdraw or deposit: ");
while(input.hasNext()) {
amount = input.nextDouble();
input.nextLine();
if(chosenAccount.isValid(amount)){
System.out.print("Please enter a comment: ");
message = input.nextLine();
Calendar transdatetime = Calendar.getInstance();
chosenAccount.makeTransaction(new Transaction(transdatetime,message,amount));
System.out.println("");
interactionLoop();
}
}
}
答案 0 :(得分:0)
accountNr = input.nextInt();
从第2次开始Scanner
从Std InpuStream中扫描Integer
,但换行符仍然是
ssn = input.nextLine();
因为你的程序没有退出。同样适用于double
。更好地使用
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
然后使用reader.readLine()
并将其解析为所需的数据类型。例如。 Integer.parseInt(reader.readLine())