1
public class Practice {
public static void main(String []args){
Scanner ScanMe=new Scanner(System.in);
char ch,answer='K';
System.out.println("I am thinking of a letter between A and Z.");
ch=(char)ScanMe.nextInt();
System.out.println(ch);
if(answer==ch){
System.out.println("CORRECT");
}
}
}

I created a new scanner, I created my char variables and then I read my char variables in and its giving a mismatch error???

Eli
  • 687
  • 5
  • 16

3 Answers3

2

Matt's solution is correct, but I wanted to add a bit of clarification. ch=(char)ScanMe.nextInt(); throws an exception because ScanMe.nextInt() gets evaluated first. Assuming you entered a letter, nextInt would throw an exception because a letter is not a decimal integer (which nextInt expects).

However, things will work if you enter a decimal integer. For instance, if you enter 75, this method call will work, and when you cast 75 to a char, it's actually 'K', so your program as originally written would say "CORRECT".

Check an ASCII table if that casting doesn't make sense.

tyler
  • 91
  • 5
  • Oh I got it, so basically once the nextInt realizes I put anything other then an int in it automatically throws an exception and does not get cast to a char? – Eli Feb 10 '16 at 05:01
  • 1
    That's pretty much it. As soon as the exception is thrown, no more of the code is executed (until the exception is caught, if ever). – tyler Feb 10 '16 at 05:07
1

Try using this to get a char

ch = ScanMe.next().charAt(0);

also K is not the same as k.

Matt
  • 52
  • 7
  • Dude great answer, I will give u the check when it allows, also why did you put zero in the .charAt, what does that accomplish – Eli Feb 10 '16 at 04:44
  • charAt(0) makes sure it only takes the first charter you enter so if you enter abscdsfdfhfgj it only takes the a – Matt Feb 10 '16 at 04:46
0

An Integer is not a char

Try using next and then just using the first char of the String

use String.charAt(int);

https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#charAt(int)

Scary Wombat
  • 41,782
  • 5
  • 32
  • 62