0

Java Basics: Conditional Statements

I cannot get over this logical error... where every answer is incorrect. What am I doing wrong? import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner input = new Scanner(System.in); int num1 = (int) (Math.random() * 2); if ( num1 == 0) { String Heads = "Heads"; } if ( num1 == 1){ String Tails = "Tails"; } System.out.print(" Will the number be Heads or Tails? :"); String userAnswer = input.next(); String num1_1 = String.valueOf(num1); if (userAnswer == num1_1) { System.out.println("That is correct! "); } else { System.out.println("Sorry incorrect"); } } }

12th Jun 2019, 8:13 PM
Markie Alicia
Markie Alicia - avatar
2 Réponses
13th Jun 2019, 8:44 AM
Danijel Ivanović
Danijel Ivanović - avatar
+ 10
use .equals() function instead of == operator, change if() condition to (userAnswer.equals(num1_1)) always use .equals() for testing value equality of 2 strings
12th Jun 2019, 10:44 PM
Gaurav Agrawal
Gaurav Agrawal - avatar