java - 格式化数字打印输出异常

标签 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;//程序需要scanner 导入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);




    }
}

最佳答案

在第 25 行,您声明了 double item,但在第 38 行,您尝试将 input.nextInt() 分配给变量 item。

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

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

item = input.nextInt();

对此:

item = input.nextDouble();

关于java - 格式化数字打印输出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40172421/

相关文章:

java - 创建 .jar 文件

c++ - 使用 ostream 无处打印

c# - 在 .Net String.Format 中强制 double 正号

c# - 将 DateTime 转换为格式为 YYYYMMDD 的字符串

java - 在 Android 上接收和阅读 GATT 通知

java - JOptionPane 对话框未打开(JOptionPane.showMessageDialog(null ,"File Recieved Sucessfully"))

java - 具有多个 Web 应用程序的 CAS SSO

javascript - 删除消息选择打印机并使用 javascript 自动打印文档

javascript - 使用 javascript 打印 Canvas 图像

formatting - 我可以向 mercurial 命令模板添加自定义颜色吗?