if statement problem - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

if statement problem

TobuwayTobuway Posts: 12Member
[code]
if(input == "yes"||input=="y"||input=="YES")
{
String filename = JOptionPane.showInputDialog("Please name the file, it will be added to your Documents directory.");
try {
FileWriter fw =new FileWriter(filename+".txt");
PrintWriter output = new PrintWriter(fw);
output.println(a.getText());
output.close();
} catch (IOException e1) {
System.out.println("Error: "+ e1.getMessage());
}
}
else
{...
[/code]

the problem I have is that when I input "yes","y",or"YES" the program returns a false negative and goes to the else statement can anyone see why?

Comments

  • TommittajaTommittaja Posts: 10Member
    ok: i have made the excact same problem.. you cannot compare Strings on the operator ==. Strings must be compared like this:

    -----------------------------------------------------------------
    Scanner read = new Scanner(System.in);
    String s = read.nextLine();
    // here comes the important part!!
    if (s.equals("yes") || s.equals("no")) {
    // some code
    //or you can do it this way, so it won't be case-sensitive:
    if (s.equalsIgnoreCase("yes") || s.equalsIgnoreCase("no") {
    // some code
    -----------------------------------------------------------------
    hope that helped...
    i just wondered: how can't you know that kind of thing, when you do things so complicated in the rest of the code?
  • TobuwayTobuway Posts: 12Member
    "i just wondered: how can't you know that kind of thing, when you do things so complicated in the rest of the code?"

    I'm still learning, my teacher might have gone over how to handle string input like this, but it would have been a while ago.

    And thank you.
Sign In or Register to comment.