不兼容的类型双字符串

Ker*_*y G 0 java string double types

为什么购买是不兼容的类型scan.next()?(我正在尝试获取用户输入以进行购买和招标,然后使用方法来计算更改).

public static void makeChange() //one method of a class
{       
    double purchase;
    double tendered;

    Scanner scan = new Scanner (System.in);

    System.out.println ("How much was the Purchase?");
    purchase = scan.next(); //why would this be an incompatible type?
    System.out.println ("Amount Tendered"); 
    tendered = scan.next();      

    System.out.println("Processing Transaction");
    int ch[] = cd.makeChange(purchase, tendered);

    .... continued
Run Code Online (Sandbox Code Playgroud)

ass*_*ias 5

因为scanner.next()返回一个字符串,如javadoc中所述.这是第一个检查方法何时不能按照您的想法进行检查的地方.你可能想要使用scanner.nextDouble().

正如评论中所指出的,如果您的代码不仅仅是一个练习,那么您应该使用BigDecimal作为货币金额以避免舍入问题(双精度不准确).