mardi 26 octobre 2021

not executing the if statement even when the condition is true

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.

Aucun commentaire:

Enregistrer un commentaire