格式化数字打印输出异常

时间:2016-10-21 09:00:48

标签: java printing formatting output numeric

Exception in thread "main" java.util.InputMismatchException  
    at java.util.Scanner.throwFor(Scanner.java:864)  
at java.util.Scanner.next(Scanner.java:1485)    
at java.util.Scanner.nextInt(Scanner.java:2117)     
at java.util.Scanner.nextInt(Scanner.java:2076)     
at Commission2.main(Commission2.java:38)

一开始就运作良好,直到一切都崩溃了。现在我需要帮助。任何人吗

import java.util.Scanner; //程序需要scaanner import java.text.DecimalFormat;

public class Commission2
{

public static void main(String args[])

    {

        //create Scanner
    Scanner input = new Scanner(System.in);

    //format decimal with two digits
    DecimalFormat twoDigits = new DecimalFormat("0.00");
    //format decimal with three digits
    DecimalFormat threeDigits = new DecimalFormat("0.000");

    //declare all variables
    int size,count = 0;
    int pay = 200;
    double commission = 9/100;
    double result = 0;
    double item, itemtotal = 0;

    //get the limit of the data entry (data validation technique)
    do{
        System.out.printf("Enter the number of items :");
            size = input.nextInt();

    }while(size < 0);

    //data entry
    while (count < size) {

        System.out.print("Enter price of item #" +(count + 1) +": ");
            item = input.nextInt();


        /*Processing!*/
        itemtotal += item;
        ++count;


    }//end while
        result = (itemtotal * commission) + pay;

    System.out.printf("%s%d\n","The total earnings for this week is $",result);




    }
}

4 个答案:

答案 0 :(得分:1)

System.out.printf("%s%f\n", "The total earnings for this week is $", result);

可行,因为%d仅使用整数,而%f适用于浮点数和双精度数。

答案 1 :(得分:1)

在第25行,您宣布double item,但在第38行,您正尝试将input.nextInt()分配给变量项。

如果您在此处提供Integer值(5),则代码应按预期工作。但是,当提供Double时(5,12),将抛出InputMismatchException异常。

要解决此问题,只需更改此内容:

item = input.nextInt();

到此:

item = input.nextDouble();

答案 2 :(得分:0)

因为它在item = input.nextInt()失败; 当您输入值时,它看起来好像没有尝试使用int值。请检查一下。 为什么不发布您使用过的输入?

答案 3 :(得分:0)

在你的printf中,你使用十进制整数格式来打印浮点数/双打。 而不是%d使用%f。

Please have a look at this link for more information