Jump to content

I need help with a very simple problem

- - - - -

  • Please log in to reply
4 replies to this topic

#1
Walizzay

Walizzay

    Newbie

  • Members
  • Pip
  • 5 posts
Hello, im new to java programming and i ran into what seems to be(and most likely is) a very simple problem. Im testing a string variable with an if statement and its not working how i want it to be:


import java.util.Scanner;

import java.util.Random;


public class Program {

	public static void main(String[] args){

		Scanner keyboard = new Scanner(System.in);  //scanner variable to get user input

		

		String option;

		

		System.out.println("Welcome!");

		System.out.print("Do you want to play the game?");

		option = keyboard.nextLine();  //storing input.

		

		

		if(option == "Yes"||option=="yes"){

			System.out.println("Ok then!!! Lets play!");

		}

		else{

			System.out.println("\n");

			System.out.println("Alright! bye!");

			

		}

	}

}


when i run this, i input "yes" into the command line and it goes straight to the "else" statement instead of running the code in the if statement. Can anyone help me and tell me what im doing wrong? Thanks a lot in advance! :)

#2
Xdawn90

Xdawn90

    Learning Programmer

  • Members
  • PipPipPip
  • 55 posts
Use the equal() method instead of "==" operator. "==" operator compares object references and not the value of the string variable.

import java.util.Scanner;
import java.util.Random;

public class Program {
    public static void main(String[] args){
        Scanner keyboard = new Scanner(System.in);  //scanner variable to get user input
        
        String option;
        
        System.out.println("Welcome!");
        System.out.print("Do you want to play the game?");
        option = keyboard.nextLine();  //storing input.
        
        if(option.equals("Yes") || option.equals("yes")){
            System.out.println("Ok then!!! Lets play!");
        }
        else{
            System.out.println("\n");
            System.out.println("Alright! bye!");
            
        }
    }
}
Java String comparison. The difference between == and equals().

#3
Walizzay

Walizzay

    Newbie

  • Members
  • Pip
  • 5 posts
Thank you so much!

#4
johannes

johannes

    Newbie

  • Members
  • Pip
  • 6 posts

Xdawn90 said:

if(option.equals("Yes") || option.equals("yes")){

If possible you should try to use equals operator on the constants, because an object like 'option' can be null. Also, if your intention with checking both Yes and yes is to not care about the case, you can use the equalsIgnoreCase() method

if("Yes".equalsIgnoreCase(option)){


#5
Walizzay

Walizzay

    Newbie

  • Members
  • Pip
  • 5 posts
Thats brilliant, thanks a lot!




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users