【问题标题】:Java Beginner:nextLine problems, while and if loop errorsJava Beginner:nextLine 问题,while 和 if 循环错误
【发布时间】:2020-04-17 20:31:50
【问题描述】:

您好,我 3 天前开始使用 Java,我正在做一个小型银行账户项目,询问用户的姓名和余额,并根据输入打印出一些消息。 我的问题从尝试验证用户名是否正确开始。无论如何,这是代码

//代码开始 包 com.chief;

导入 java.util.Scanner;

公共类主{

public static void main(String[] args) {

    int minAmount = 500;

    Scanner userInput = new Scanner(System.in);
    /* String verifyName = "Yes";*/

    System.out.println("Please enter your Account Name and Balance");
    System.out.println("Account Name: ");


    //Username here
    String userName = userInput.nextLine();
    System.out.println("Balance: ");

    //Account balance here
    double balance = userInput.nextDouble();
    System.out.println("Account Name: " + userName);


    // Verification
    System.out.println("Please verify your username, enter Yes to accept or No to cancel");
    String verifyName = userInput.nextLine();

    while (verifyName.equals("Yes")) {
        if (balance < 500) {
            System.out.println("Your balance is below the minimum requirement of " + minAmount + " please top up");
            System.out.println("Thank you for banking with King Solomon Bank");
            }
        if (balance > 500){
            System.out.println("Good");
        }
    } 
}

}

程序在要求用户输入是或否后终止,但我认为它在我第一次尝试时有效。所以我无法输入那个字符串

另外,我在使用 verifyName 的输入来运行 while 和 if 循环时遇到了麻烦。 任何帮助是极大的赞赏。 谢谢

【问题讨论】:

标签: if-statement while-loop


【解决方案1】:

需要以下修复:

    String verifyName = userInput.next(); // not nextLine()!

    if (verifyName.equalsIgnoreCase("Yes")) {  // you get to endless loop here, use case-insensitive comparison

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-25
    • 1970-01-01
    • 2019-08-21
    • 2012-08-04
    • 2014-04-26
    • 2021-12-10
    • 1970-01-01
    相关资源
    最近更新 更多