我的while语句不适用于我的BigDecimal

时间:2014-04-01 17:23:34

标签: loops while-loop bigdecimal

    public static void main(String[] args) {

    //Creates the BigDecimal and scanner used
    BigDecimal answer = new BigDecimal("0");
    Scanner scan = new Scanner(System.in);

    //While statement to repeat if they dont answer 1 or 2
    while (! answer.equals("1") && ! answer.equals("2")) {
        //Asks user to input the number 1 or 2
        System.out.print("Enter the number 1 or 2: ");
        //Takes in users answer
        answer = scan.nextBigDecimal(); 
    }

    //Uses printf to print what they typed in
    System.out.printf("You entered the number %s.", answer);
    scan.close();

}

此代码无效,我想知道原因。问题似乎在while语句中,我似乎无法找到问题。请帮忙

1 个答案:

答案 0 :(得分:1)

这里

while (! answer.equals("1") && ! answer.equals("2")) {

您正在将BigDecimal对象与字符串进行比较" 1"和" 2"。

这个怎么样?

while (! answer.equals(new BigDecimal("1")) && ! answer.equals(new BigDecimal("2"))) {