Gerald Loo Gerald Loo - 1 month ago 12
Java Question

Formatting Numeric Print Output Exception

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)


It was working well at the beginning, until everything came crashing down. Now I need help. Anyone?

import java.util.Scanner;//program needs 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);




}
}

Answer

On line 25 you are declaring double item, yet on line 38 you are trying to assign input.nextInt() to the variable item.

If you were to provide an Integer value (5) here, the code should work as intended. However when a Double is provided (5,12) an InputMismatchException exception will be thrown.

To fix this simply change this:

item = input.nextInt();

to this:

item = input.nextDouble();
Comments