0

This is the program

import java.util.Scanner; //imports class

public class blank2 {

    public static void main(String[] args) {

     Scanner in = new Scanner(System.in);
     boolean valid = true;
     String ans;
     ans = in.next(); //answer is a string

If you type in "y", it goes right to the else statement.

while (valid == true)
{

it always skips this statement

    if (ans == "y")
    {
       System.out.println("it works");
       valid = false;
    {
    else
    {   
       System.out.println("no work");
       valid = false;
    {   
}   


   }

}

It just wont work

2 Answers2

6
 if (ans == "y")

Don't compare strings with ==. That compares object references(the same string). Use:

 if ("y".equals(answer))

instead. It will compare strings for equality(check if they are identical as opposed to the same one). I do not use answer.equals("y") due to the risk of a null pointer exception if answer was null for any reason.

nanofarad
  • 40,330
  • 4
  • 86
  • 117
0

In strings, don't use the ==, you can use compareTo instead.

  if ("y".comprateTo(answer))

With this method you can check if they are the same, or if one is greater than the other.

let us know if you have questions

X-Pippes
  • 1,170
  • 7
  • 25
  • The code produces a type mismatch. You could use `if ("y".comprateTo(answer)==0)` but `if ("y".equals(answer))` is more intuitive and probably faster. – Daniel Oct 17 '13 at 23:06
  • yes, it's true. the `equals` was already here, I just gave @user2892492 other options to the future. – X-Pippes Oct 17 '13 at 23:07
  • @X-Pippes I would argue that compareTo isn't of very much use until one starts sorting. – nanofarad Oct 17 '13 at 23:27