Howdy, Stranger!

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

Categories

Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

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.