-2

As far as I know, the logic in conditional and loop statements are the same whether it is C# or Java.

class WhileLoops {

public static void main(String args[]){


Scanner input = new Scanner(System.in);
String answer = "";
/*do{

    System.out.println("Will you be my girlfriend?(Yes/No)");
    answer = input.nextLine();
    }while(answer != "Yes" && answer != "Yes");*/

while(answer != "Yes" && answer != "yes") {

    System.out.println("Will you be my girlfriend?(Yes/No)");
    answer = input.nextLine();
    }

System.out.println("I promise to make you feel special.");

   }
}

as you can see in the code above I used do-while and while just setting either one as a comment when I will compile and run.

This is what happens when I run the program: 1

Emil Laine
  • 41,598
  • 9
  • 101
  • 157
Andre
  • 101
  • 9
  • 1
    Your code writes out an image? Please copy your sample input and output into your question! There is no need for an image here. – Jongware Oct 11 '15 at 09:39
  • Is it hard to load? Okay will do better next time thank you :) – Andre Oct 12 '15 at 08:24

2 Answers2

2

Use the .equals() method. So,

while(answer.equalsIgnoreCase("yes")) {... }

The reason for this is that Java compares references when using the == operator. When you compare the two strings they point at different places in memory, and so the comparison fails.

The equals() (and equalsIgnoreCase()) methods compare the actual contents of the block of memory.

Note: This is only true for reference types (like strings and other classes). Value types (like ints and floats etc) can be compared with the usual equals operators.

Jongware
  • 22,200
  • 8
  • 54
  • 100
Colin Grogan
  • 2,462
  • 3
  • 12
  • 12
0

Use this :

while(!answer.toLowerCase().equals("yes"))
Rahman
  • 3,755
  • 3
  • 26
  • 43