Results 1 to 12 of 12
  1. #1
    javajames is offline Member
    Join Date
    May 2011
    Posts
    32
    Rep Power
    0

    Question Comparing characters.

    I am writing a code (a beginners code, i set myself targets for a simple program, and along the way i pick up all the extra details about java) and i want to be able to ask the user a yes or no answer and test that in a condition. Here is what i wrote (narrowed down to just the necessary code);
    Java Code:
    import java.util.Scanner;
    
    class choice {
        public static void main(String[] args) {
            System.out.println("(y/n):");
            Scanner scan = new Scanner(System.in);
            String ch = scan.nextLine();
            if (ch=="y") { System.out.println("you chose yes (y)"); }
            else if (ch=="n") { System.out.println("you chose no (n)"); }
            else { System.out.println("you didn't choose yes or no!"); }
        }
    }
    This compiles perfectly well, but when i enter the y or n (or anything for that matter) it just passes to the else statement. Always. So i tried using char and all its ways, that didnt compile right. Then using int, which compiled, but--
    Java Code:
    import java.util.Scanner;
    
    class choice {
        public static void main(String[] args) {
            System.out.println("(y/n):");
            Scanner scan = new Scanner(System.in);
            int ch = scan.nextInt();
            if (ch=='y') { System.out.println("you chose yes (y)"); }
            else if (ch=='n') { System.out.println("you chose no (n)"); }
            else { System.out.println("you didn't choose yes or no"); }
        }
    }
    This compiles correctly but throws up an exception (see below) when either n or y is selected:
    Java Code:
    james@james-laptop:~/Desktop/coding/Jcoding/examples$ java choice
    (y/n):
    y
    Exception in thread "main" java.util.InputMismatchException
    	at java.util.Scanner.throwFor(Scanner.java:857)
    	at java.util.Scanner.next(Scanner.java:1478)
    	at java.util.Scanner.nextInt(Scanner.java:2108)
    	at java.util.Scanner.nextInt(Scanner.java:2067)
    	at choice.main(choice.java:7)
    am i comparing strings or characters incorrectly? (im using jdk on linux btw)

    Thanks in advance.

  2. #2
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    You compare objects(which a string is) with equals. Chars can be compared with ==.

    Try
    Java Code:
    char c = 'y';
    System.out.println(c == 'y');

  3. #3
    Solarsonic is offline Senior Member
    Join Date
    Mar 2011
    Posts
    261
    Rep Power
    4

    Default

    An InputMismatchException is thrown when the received input type does not match the desired input type. In this case you asked for an int, but inputted something that isn't an int.

  4. #4
    javajames is offline Member
    Join Date
    May 2011
    Posts
    32
    Rep Power
    0

    Default

    ok, so we have ruled the bottom one out, there is still the matter of my original code, why wont it recognize my input if it is comparing a string to a string (supposedly)

  5. #5
    Solarsonic is offline Senior Member
    Join Date
    Mar 2011
    Posts
    261
    Rep Power
    4

    Default

    Quote Originally Posted by javajames View Post
    ok, so we have ruled the bottom one out, there is still the matter of my original code, why wont it recognize my input if it is comparing a string to a string (supposedly)
    Because you're asking for an int... hence nextInt().

  6. #6
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,271
    Rep Power
    25

    Default

    the matter of my original code
    Please post the line(s) of code you're talking about.

  7. #7
    javajames is offline Member
    Join Date
    May 2011
    Posts
    32
    Rep Power
    0

    Default

    what scanner is used with characters?

  8. #8
    javajames is offline Member
    Join Date
    May 2011
    Posts
    32
    Rep Power
    0

    Default reply

    new code, based on others suggestions, cant get character scanner to work:
    Java Code:
    import java.util.Scanner;
    
    class choice {
        public static void main(String[] args) {
            System.out.println("(y/n):");
            Scanner scan = new Scanner(System.in);
            char ch = scan.next();
            if (ch=='y') { System.out.println("you chose yes (y)"); }
            else if (ch=='y') { System.out.println("you chose no (n)"); }
            else { System.out.println("rrrrrrrrrgggggg, i hate you"); }
        }
    }

  9. #9
    javajames is offline Member
    Join Date
    May 2011
    Posts
    32
    Rep Power
    0

    Default

    wait, scanner doesn't take char

  10. #10
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Scanner#next() and Scanner#nextLine() return String objects. You should be able to easily extract the first (and only) character in the String via the String charAt(0) method.

  11. #11
    javajames is offline Member
    Join Date
    May 2011
    Posts
    32
    Rep Power
    0

    Default crude method

    ok, i've done it, but slightly crude isn't it? oh well, works!
    Java Code:
    import java.util.Scanner;
    
    class choice {
        public static void main(String[] args) {
            System.out.println("(y/n):");
            Scanner scan = new Scanner(System.in);
            String ch1 = scan.nextLine();
            char ch = ch1.charAt(0); //turns string into char
            if (ch=='y') { System.out.println("you chose yes (y)"); }
            else if (ch=='n') { System.out.println("you chose no (n)"); }
            else { System.out.println("rrrrrrrrrgggggg, i hate you"); }
        }
    }
    thank you all

  12. #12
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by javajames View Post
    ok, i've done it, but slightly crude isn't it? oh well, works!
    Why "crude"?

    The main suggestion I'd have would be to change your String to lower case so that the code works even if the user presses Y or N, fix your indentation and use of braces so that the code is better spread out and readable, and check to be sure that the String is one char long. If no char's entered, you'll get an exception if you try to convert the 1st char in the String to a char. Also it's a good habit to close resources when done with them, including the Scanner object.

    Java Code:
          System.out.println("(y/n):");
          Scanner scan = new Scanner(System.in);
          String ch1 = scan.nextLine().toLowerCase();  // so it works if they enter Y or N
          if (ch1.length() == 1) {
             char ch = ch1.charAt(0); // turns string into char
             if (ch == 'y') {
                System.out.println("you chose yes (y)");
             } else if (ch == 'n') {
                System.out.println("you chose no (n)");
             } else {
                System.out.println("rrrrrrrrrgggggg, i hate you");
             }
          } else {  // if String is not one char long
             // print out error message
          }
          scan.close();  // may want to do this in the finally block of a try/catch block

Similar Threads

  1. comparing Graphs and Comparing Matrix
    By jetnor in forum New To Java
    Replies: 0
    Last Post: 03-27-2011, 01:40 AM
  2. Replies: 1
    Last Post: 10-21-2010, 07:06 PM
  3. Comparing arrays
    By mitty in forum New To Java
    Replies: 8
    Last Post: 04-14-2010, 11:55 AM
  4. Comparing dates
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 01-28-2008, 09:02 AM
  5. comparing
    By Feng in forum New To Java
    Replies: 2
    Last Post: 11-23-2007, 09:40 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •