Home > Blockchain >  not executing the if statement even when the condition is true
not executing the if statement even when the condition is true

Time:10-27

I have made a java code to play hangman game. I have given the user 15 chances to guess the word and once the user has guessed the correct answer it should execute the if statement but it does not. I have tried to solve this problem many times but it is never working. I would appreciate it if you could tell me the problem and give a suitable solution without making much change in my code.

My code:

import java.util.*;
public class game
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        String list[] = {"apple", "banana", "mango", "kiwi", "coconut", "papaya", "lichi", "strawberry", "orange", "cherry"};
        int rand = (int)(Math.random()*9) 0;
        String word = list[rand];
        String ask = "_";
        for(int i = 1; i < word.length();i  ){
            ask = ask   "_";
        }
        System.out.println(ask);
        System.out.println("hint: It is a fruit");
        ArrayList<String> ans = new ArrayList<String>();
        for (char i : ask.toCharArray()){
            ans.add("_");
        }
        for (int j = 1; j<=15; j  ){
            System.out.println("Enter a character: ");
            String input = in.next();
            char alt = input.charAt(0);
            int x = 0;
            for (char i : word.toCharArray()){
                if(alt == i){
                    ans.set(x, input);
                }
                x  ;
            }
            for (String i : ans){
                System.out.print(i);
            }
            int y = 0;
            ArrayList<String> answer = new ArrayList<String>();
            for (char i : word.toCharArray()){
                answer.add("_");
            }
            for(char i : word.toCharArray()){
                String alternate = String.valueOf(i);
                answer.set(y, alternate);
                y  ;
            }
            if (ans == answer){
                System.out.println("\nyou win");
                break;
            }
            System.out.println("\n" ans);
            System.out.println(answer
            );
        }
    }
}

Due to so many many unsuccessful attempts my code may have some unnecessary lines which are making the long.

CodePudding user response:

when you use == it compares whether these two reference variables are pointing to the same object or not. if you want to compare their content then you should use the equals() method which compares the content of the object, not the object itself.

use ans.equals(answer) instead of ans== answer

CodePudding user response:

Try using equals() method instead of ==.

if (ans.equals(answer)){
  • Related