-2

so I was working on a program for school in Java and I am using Eclipse on mac osx. When I run the program it gives me this error:

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 Dank.main(Dank.java:13)

This is the code:

             import java.util.Scanner;
             public class Dank
           {
 static Scanner in = new Scanner(System.in);
 public static void main(String args[])
{
int antonio='0';
int answer;
System.out.print("Whats your name? ");
answer = in.nextInt();
if (answer == antonio) {
    System.out.println("are you sure? you are a Dank Meme "+answer);
}
else
{
        System.out.println("Damn, you aren't a Dank Meme "+answer);
}
  }
  }
  • 3
    You need to include your actual code in your question, not a link to a picture of your code. – azurefrog Feb 09 '17 at 23:06
  • 2
    Please post the necessary code to reproduce the problem as plain-text here (**no** images, links, etc.). – Paul Feb 09 '17 at 23:06
  • Just put the line of the "static Scanner ..." INTO and not OUT of the main, you'll never get code like this out of nowhere, not in a method – azro Feb 09 '17 at 23:07
  • 2
    Possible duplicate of [No Such Element Exception?](http://stackoverflow.com/questions/8032099/no-such-element-exception) – Paul Feb 09 '17 at 23:09

1 Answers1

0

the in.nextInt() only allowing integer as an input. So if you input a string it will give you inputmismatchexception. try to change it to in.nextLine(). your condition earlier. it doesn't read '0' as 0. the program reads it as character of '0' so it returns 48 because you gave it to an int. try to use this code.

 public class TestClass {


 static Scanner in = new Scanner(System.in);
public static void main(String args[])
{
String antonio = "0";
String answer;

System.out.print("Whats your name? ");
answer = in.nextLine();
if (answer .equalsIgnoreCase(antonio) ) {
System.out.println("are you sure? you are a Dank Meme "+answer);
}
else
{
 System.out.println("Damn, you aren't a Dank Meme "+answer);
}
}

}
Mr.Aw
  • 216
  • 2
  • 14
  • and as for comparison of string if you need. (answer .equalsIgnoreCase(antonio) ) instead of using "==" – Mr.Aw Feb 10 '17 at 02:18