Java代码无故跳行

问题描述 投票:0回答:1

该方法中绕过了 Scanner 对象,我不知道为什么。没有错误或变暖。它只是跳过它。

` 公共类 AccountView 扩展 AccountController{

Scanner input = new Scanner(System.in);
AccountController account = new AccountController();

public void createNewAccount() {
    System.out.println("Enter account number: ");
    account.setAccountNumber(input.nextInt());
    
    System.out.println("Enter account holder: "); //<--- Prints this
    account.setHolderName(input.nextLine()); < --- But ignores that one
    
    System.out.println("There is a initial deposit? (y/n)");
    String initialDepositOption = input.nextLine();
    
    if(initialDepositOption.equalsIgnoreCase("y")) {
        System.out.println("Enter the initial deposit value: ");
        account.setAmount(input.nextDouble());
    }
    
    System.out.println(toString());
}`

再次强调:没有 IDE 或运行时错误。会发生什么?

我尝试在 Scanner 对象上使用 .close() 并再次调用它。它返回一个错误,指出扫描仪已关闭。然后尝试使用 println() 添加一些“间隔符”。没有发生任何不同的事情。

java error-handling
1个回答
0
投票

这是因为扫描int后没有清除缓冲区。 它扫描 int,但将行的其余部分留空并准备好扫描,因此当您调用 input.nextLine() 时,它会从 int 输入中获取剩余的行,这恰好什么也没有,但仍然足以搞乱您的输入。您可以在调用 input.nextInt() 之后添加一行,其中仅显示 input.nextLine();这将清除缓冲区并解决任何问题

© www.soinside.com 2019 - 2024. All rights reserved.