For some reason, when I type in the answer, nothing happens, whoever can help me fix that code, I thank you

Asked

Viewed 34 times

0

For some reason, when I type in the answer, nothing happens, anyone who can help me to fix it, I thank you

import java.util.Scanner;

public class Main {
public static void main(String[] args){         
    Scanner in = new Scanner(System.in);
    String resposta;
   System.out.println("Quanto é 2 + 2?");
   resposta = in.nextLine();
   if(resposta == "4")
       System.out.println("Resposta correta!");
   
            
}

}

  • string must be compared with equals, if("4".equals(resposta)) should already work

1 answer

1

When we’re working with String, the best way to make comparisons is by using the .equals(elemento) and not the "==". The latter should only be used when we are using primitive types. For example; int, double, Boolean. Hugs!

if(resposta.equals("4")) {
   System.out.println("Resposta correta!");         
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.