gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 02:46:06 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com