创建用于在Java中存入和取出资金的if语句

时间:2015-09-07 02:57:09

标签: java

我一直试图找出为什么我的代码在用户决定是否要从他们的帐户中提款或存款后不再进入我的if语句。

这是我目前的输出:

Would you like to withdraw or deposit money? 
132.0
The date the account was created: Sun Sep 06 22:28:46 EDT 2015

当它到达“你想撤回或存款吗?”它不再允许用户输入任何文本。所以我的问题是,我该怎么做才能纠正这个问题?

以下是我当前代码的片段:

public class T6 {
    public static void main(String[] args) {

        System.out.println("Enter the annual interest rate: ");
        interestRate = scan.nextDouble();

        System.out.println("Would you like to withdraw or deposit money? ");
        String input = scan.nextLine();

        if (input.equals("withdraw")) {
            System.out.println("Enter the amount you would like to withdraw: ");

        } else if (...) {
          ...
          }

    } // End of main method.

} // End of class header.

2 个答案:

答案 0 :(得分:1)

关于nextLine()的文件指出:

  

使此扫描程序超过当前行并返回该输入   被跳过了。 此方法返回当前行的其余部分,   排除末尾的任何行分隔符。该位置设置为   下一行的开头。由于此方法继续搜索   通过输入寻找行分隔符,它可以缓冲所有   如果没有行分隔符,则搜索要跳过的行的输入   本。

那么,你的情况会发生什么,因为你没有在你的行之前调用任何nextLine()

System.out.println("Would you like to withdraw or deposit money? ");

JVM认为您输入的上一行分隔符是您需要读取的行。问题的解决方案可能是您至少应该调用nextLine()一次以清除行前的缓冲区:

System.out.println("Would you like to withdraw or deposit money? ");

像这样:

scan.nextLine();    
System.out.println("Would you like to withdraw or deposit money? ");
String input = scan.nextLine();

答案 1 :(得分:0)

你的代码看起来不错。但问题不在于代码。同时为你的程序提供输入。下面的步骤你需要输入文字"撤回"或者"存款" 但是你输入了号码。

String input = scan.nextLine()

输入应退出或存入

if (input.equals("withdraw")) {} //this ur logic saying

但是你没有给你的程序提供正确的输入,比如撤回或存款

Would you like to withdraw or deposit money? 
132.0
相关问题