-3

I have a switch and an if statement, and they are equivalent. They should both take a string, if yes do something, and if no do another thing. The if statement does nothing regardless of what is entered, but the switch statement does. Why is that?

Here is the if statement:

if (yes.equals("yes")){
    System.out.println ("Enter your first number");
    fnum = x.nextDouble();
    System.out.println ("Enter your second number");
    snum = x.nextDouble();
    calculations(fnum, snum);
}
if (yes.equals("No")) {
    System.out.println("okay, bye then!");
}

Here is the switch:

switch (yesno){
    case "yes":  
        System.out.println ("Enter your first number");
        fnum = x.nextDouble();
        System.out.println ("Enter your second number");
        snum = x.nextDouble();
        calculations(fnum, snum);
        break;
    case "no":
        System.out.println("k bye");

This is not a duplicate, because the issue is in the if statement. I have been marked duplicate for my switch.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Ruchir Baronia
  • 7,406
  • 5
  • 48
  • 83

1 Answers1

2

I have a switch and an if statement, and they are equivalent.

Actually, they are NOT equivalent:

  • The if version is checking for "yes" or "No". But the switch version of checking for "yes" or "no". Since the checks are case sensitive in both cases, you will get different results if the input is "no" ... or "No".

  • The two versions check different variables; i.e. yes and yesno. This could make a difference, depending on the context.

Either of these could explain the different behaviour you are seeing.


I thought that yes and yesno would be equal, but they weren't...? Any idea why?

Well, clearly the names are different so they cannot be the same variables.

However, the fact that they are different variables does not necessarily mean that they have different values. It is the values that determine the code's behaviour.

Certainly, if yesno contained a proper "yes" or "no" value and yes contained something else (such as ""), then that would give the behaviour you are observing. (Obviously this is a hypothetical diagnosis. If you want a more concrete answer, show us the relevant code.)

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216