-1

I'm trying to make a program that can read whatever the user inputs and checks their input using if..else statement.

import java.util.Scanner;

class Answers{

        public void FalseAnim() {
            System.out.println("Game Over your answer is wrong. try again!");
        }

        public void CorrectAnim() {
            System.out.println("your answer is correct");
        }
}

public class quizgame {
    public static void main (String[] args) {
        Scanner input = new Scanner(System.in);
        Answers ans = new Answers();
        String strans1;
        System.out.println("welcome to the quiz game!");
        System.out.println("what is 1+1");
        strans1 = input.nextLine();
        if (strans1=="two"||strans1=="2") {
            ans.CorrectAnim();
        }
        else {
            ans.FalseAnim();
        }

    }
}

every time I run the program and input anything it goes straight into the else statement, even when I input either a "2" or a "two"

1 Answers1

0
if ("two".equals(strans1)||"2".equals(strans1))

will work.

In your code, you are comparing references and not the value. Hence it is returning false either way.

Sibgha
  • 479
  • 3
  • 10