dimanche 2 août 2015

InputMismatchException: String not recognized

I wrote the piece of Java code below. When running it and typing in any value (either one defined, e.g. latte, or any other, e.g. az integer), I get an InputMismatchException.

As far as I could find answers, this exception means that the input type does not match the expected type. What am I missing, why isn't the code recognizing a String input? Thanks for the supprort.

Cheers, Gabor

package Lesson1;

import java.util.Scanner;

public class Coffee {

    public static void main(String[] args) {

        //I define the type of coffees as Strings, plus the order as String as well
        String espresso = "espresso";
        String americano = "americano";
        String cappuccino = "cappuccino";
        String latte = "latte";
        String order = new String();

        //I ask the user for their input
        Scanner choice = new Scanner(System.in);
        System.out.println("What kind of coffee would you like? We have: espresso, americano, cappuccino and latte");

        //depending on the user's choice, the corresponding name is displayed; if any other string is entered, the else clause is displayed
        if (order.equals(choice.next(espresso))) {
            System.out.println("Your order: " + espresso);

        } else if (order.equals(choice.next(americano))) {
            System.out.println("Your order: " + americano);

        } else if (order.equals(choice.next(cappuccino))) {
            System.out.println("Your order: " + cappuccino);

        } else if (order.equals(choice.next(latte))) {
            System.out.println("Your order: " + latte);

        } else {
            System.out.println("Unfortunately we can't serve you. Have a nice day!");
        }

    }

}



Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at Lesson1.Coffee.main(Coffee.java:22)

Aucun commentaire:

Enregistrer un commentaire