Friday, October 19, 2018

java.util.scanner - Java Scanner - why do I get this error?





I'm not new to java, but I cannot figure out why I get this Scanner error. The code compiles fine, but I get the following runtime error



Enter item number: Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)

at java.util.Scanner.nextInt(Scanner.java:2050)
at TestInvoice.getValues(TestInvoice.java:3



import java.util.Scanner;


public class TestInvoice {


public static void main(String [] args)

{
/* create objects */
Invoice item1 = new Invoice();
Invoice item2 = new Invoice();
Invoice item3 = new Invoice();

/* get values */
getValues(item1);
getValues(item2);
getValues(item3);


/* print objects */
System.out.println(item1.toString() + "\n");
System.out.println(item2.toString() + "\n");
System.out.println(item3.toString() + "\n");


}

private static void getValues(Invoice invoice)

{
int number;
String name;
int quantity;
double price;

/* get values from user */
Scanner scanner = new Scanner("System.in");

System.out.print("Enter item number: ");

number = scanner.nextInt();

System.out.print("Enter item name: ");
name = scanner.next();

System.out.print("Enter quantity: ");
quantity = scanner.nextInt();

System.out.print("Enter item price: ");
price = scanner.nextDouble();


System.out.println();

/* set the values */
invoice.setItemNumber(number);
invoice.setItemName(name);
invoice.setItemQuantity(quantity);
invoice.setItemPrice(price);

}

}

Answer



Perhaps change



Scanner scanner = new Scanner("System.in");


to




Scanner scanner = new Scanner(System.in);

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...