如何使用Scanner.nextDouble()修复循环错误

时间:2014-12-17 06:58:20

标签: java java.util.scanner

我的代码遇到了一个循环错误,我正在使用Scanner从前两个使用带有分号分隔符的.nextLine()获取用户的输入,问题在于.nextDouble()

import static java.lang.System.out;

import java.util.ArrayList;
import java.util.Scanner;

public class UseAccount {

  public static void main(String args[]) {
    //Scanner declaration
    Scanner keyboard = new Scanner(System.in);

    //Change the delimiter
    keyboard.useDelimiter(";");
    Account myAccount;
    Account yourAccount;

    myAccount = new Account();
    yourAccount = new Account();

    out.println("Account 1 name: ");
    myAccount.name = keyboard.nextLine();
    out.println("Account 1 address: ");
    myAccount.address = keyboard.nextLine();
    // Issue is here
    out.println("Account 1 balance: ");
    myAccount.balance = keyboard.nextDouble();

    out.println("Account 2 name: ");
    myAccount.name = keyboard.nextLine();
    out.println("Account 2 address: ");
    myAccount.address = keyboard.nextLine();
    out.println("Account 2 balance: ");
    myAccount.balance = keyboard.nextDouble();

    out.print(myAccount.name);
    out.print(" (" + myAccount.address + ") ");
    out.print("has $" + myAccount.balance);
    out.println();

    out.print(yourAccount.name);
    out.print(" (" + yourAccount.address + ") ");
    out.print("has $" + yourAccount.balance);
    out.println();

    keyboard.close();
  }
}

早期宣布的帐户类是:

public class Account {
    String name;
    String address;
    double balance;

输出目前看起来像这样:

Account 1 name:
John Doe
Account 1 Address:
1234 Main St
Account 1 Balance:
30.22.
<Blank>
<Blank>

帐户1之后的预期输出余额应该导致相同的设置,而不是帐户2。

我的代码有什么问题?

1 个答案:

答案 0 :(得分:1)

问题在于您的分隔符模式。检查删除它,它应该工作。 我尝试删除分隔符,它工作正常。不要担心空格字符,因为您已经使用nextLine()接受输入。