1

Possible Duplicate:
How do I compare strings in Java?

in my java app. To accept a challenge you press y but the program doesnt continue. Can anyone help me with this?

Here is my code:

import java.util.Scanner;


    public class MainApp 
    {


        public static void main(String[] args)
        {
            Scanner scanner = new Scanner(System.in);
            System.out.println("Hello User");
            System.out.println("Please Enter your first name");
            String name;
            name =scanner.next();

        System.out.println("\n" + " Hello " + name + "how are you today?");
        String y="";
        y=scanner.next();


        System.out.println("\n" + " Well " +  name + " I am " + y + " Too." +"\n" + " I have a riddle for you " + name + ", wll you Attempt it?" + "\n" + " Type y for yes , or n for no");
        String v;
        v=scanner.next();


        if(v == "y")
            {
            System.out.println("\n" + "How much wood could a wood chuck chuck if a wood chuck could chuck wood? :) " );
            }

        else if(v == "n")
            {
            System.out.println("Ok then " + name + " suit youself, Goodbye! :) ");
            }
        else 
            { 
            System.out.println("Please pick y, or n , and make sure it is in lower case");
            }

        }

    }
Community
  • 1
  • 1
Pendo826
  • 1,002
  • 18
  • 47

2 Answers2

6
if(v == "y")

You should use String.equals() to compare strings.

so the code for the condition should be along the lines of:

if ("y".equals(v)) //checking "y".equals() prevents null access if v is null

Explanation:
The operator== is checking for identity - if the two operands are the exact same object. This is not what you want, since it is seldom the case with strings.

The equals() method on the other hand - checks for equality if the two objects equal each other.

amit
  • 175,853
  • 27
  • 231
  • 333
  • Thanks amit. Il mark as accepted as soon as i can. – Pendo826 Oct 04 '12 at 12:13
  • 1
    @Pendo826: You are welcome. Also, if you want to repeat the question if the user inserted a loop which is not y/n - you should put the `scanner.next()` and input checking in a [while loop](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html). You should try it out! (If you find troubles doing so, you should put it as a new question, but give it a try first) – amit Oct 04 '12 at 12:19
2

Use String.equals rather than the == operator as it is unlikely that the 2 String objects being compared will have the same object reference (be the same object).

if ("y".equals(v)) {
...

or better

if ("y".equalsIgnoreCase(v)) {
...
Reimeus
  • 158,255
  • 15
  • 216
  • 276