View Single Post
Old Jun 7th, 2005, 1:50 PM   #1
shangnyun
Programmer
 
shangnyun's Avatar
 
Join Date: Jun 2005
Posts: 34
Rep Power: 0 shangnyun is on a distinguished road
Logical Error... :/

Help me out here, boys. I'm a newb-programmer and am really liking Java so far. I'm stuck on this problem though. Here's the code:

import java.util.*;

public class FirstProgram
{
    public static void main(String[] args)
    {
        System.out.println("Hello out there.");
        System.out.println("Want to talk some more?");
        System.out.println("Answer y for yes or n for no.");

        Scanner scannerObject = new Scanner(System.in);
        String answerLetter;
        answerLetter = scannerObject.next();
        
        if (answerLetter == "y")
            System.out.println("Nice weather we are having.");
        if (answerLetter == "n")
        	System.out.println("Good-bye.");

        System.out.println("Press Enter key to end program.");
        String junk;
        junk = scannerObject.next();
    }
}
This is a problem from my book. I took the provided source-code and was supposed to change it around so that the program returns something when the user inputs the char "n". Now, this source-code comes from a book that was originally based on Java 1.4.2, so the author, Walter Savitch, provided a keyboard input class called SavitchIn.java. I have his class and could use it, but I figured I might as well try getting used to the newly introduced Scanner class in Java 5.0. Well, I'm not so sure if that was a good idea anymore. The Scanner class is driving me NUTS.
The problem here is that I need to input a CHAR from the keyboard. I searched myself dumb to find if there is a char-specific input method for the Scanner class, and found nothing. There are

nextInt();
nextDouble();
nextLong();
...
etc.

a bunch of them like that... but no nextChar(); exists! So I figured I could try using the method for String input instead, which is just next();
So far, so good. I used this at first:

 
if (answerLetter = "y")
    System.out.println("Nice weather we are having.");
if (answerLetter = "n")
    System.out.println("Good-bye.");

and I got no compile errors with this, but run-time errors. The compiler told me that boolean values are required here. I have no clue why... so I substituted the "="s with =='s and voila, no compile errors, no run-time errors. Great. BUT now the program has a logical error, which again I don't quite understand. It doesn't matter whether you input "y" or "n", it will always just print "Press Enter key to end program" instead of printing any of the strings in the IF statements

The code is obvious/simple enoug... help a brother out!
shangnyun is offline   Reply With Quote