RawGamingYT
RawGamingYT

Reputation: 41

java.util.InputMismatchException when using Scanner and .nextInt()

I am just trying to make a simple program to have some fun but i got this code here:

import java.util.Scanner;
import static java.lang.System.in;
import static java.lang.System.out;
public class test5 {

    public static void main(String[] args) {
        Scanner keyboard = new Scanner(in);
        char reply;
        reply = (char) keyboard.nextInt();
        if (reply == 'y' || reply == 'Y') {
            out.println(":-)");
        } else {
            out.println(":-(");
        }
        keyboard.close();

    }

}

And i got this output:

y
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.nextInt(Unknown Source)
        at java.util.Scanner.nextInt(Unknown Source)
        at test5.main(test5.java:9)

Upvotes: 1

Views: 409

Answers (1)

Mureinik
Mureinik

Reputation: 312257

The y and Y characters can't be converted to ints, hence the exception. Unfortunately, Scanner doesn't have a nextChar() method, but you could just use Strings instead:

String reply = keyboard.next();
if (reply.equalsIgnoreCase("y")) {
    out.println(":-)");
} else {
    out.println(":-(");
}

Upvotes: 1

Related Questions