我正在创建一个简单的佣金计算器,而人们可以输入无限量销售的最终销售价格;然后在最后它打印出佣金总额加上基本工资率(200美元)。
这是我的初始代码:
import java.util.Scanner;
public class AssignmentsModule2_Program2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Intialization Phase
double sold = 0;
double soldCounter = 0;
double baseRate = 200.00;
double commissionRate = 0.09;
System.out.print("Enter total of sold item or -1 if done: ");
int value = input.nextInt();
while (sold != -1)
{
sold = sold + value;
soldCounter = soldCounter + 1;
System.out.print("Enter price of sold item or -1 if done: ");
value = input.nextInt();
}
double totalCommission = sold * commissionRate + baseRate;
System.out.printf("%nTotal pay for the week is: %d%n", sold);
}
}
不幸的是,当我运行该程序时,会出现错误代码。
以下是错误代码:
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 assignmentsmodule2_program2.AssignmentsModule2_Program2.main(AssignmentsModule2_Program2.java:31)
Java Result: 1
有没有人可以提供帮助?
感谢。
答案 0 :(得分:1)
你的程序期望一个整数作为输入。使用float或char作为输入时抛出异常。我会使用double
变量:
import java.util.Scanner;
public class AssignmentsModule2_Program2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Intialization Phase
double sold = 0.0;
int soldCounter = 0;
double baseRate = 200.00;
double commissionRate = 0.09;
System.out.print("Enter total of sold item or -1 if done: ");
double value = input.nextDouble();
while (value > 0)
{
sold = sold + value;
soldCounter = soldCounter + 1;
System.out.print("Enter price of sold item or -1 if done: ");
value = input.nextDouble();
}
double totalCommission = sold * commissionRate + baseRate;
System.out.printf("%nTotal pay for the week is: %f%n", sold);
}
}