javaif-statementstatements

how to make code print Suspended instead of won


Code doesn't output Suspended but outputs Won when the user inputs true. Can someone help explain what have I done wrong with this code, please?

public class Main {
   public static void main(String[] args) {
       Scanner read = new Scanner(System.in);
       boolean isSuspended = read.nextBoolean();
       int ourScore = read.nextInt();
       int theirScore = read.nextInt();
       
       if(isSuspended = true){
             if(ourScore > theirScore){
               System.out.println("Won");
           } if(ourScore < theirScore){
               System.out.println("Lost");
           } if(ourScore == theirScore){
               System.out.println("Draw");
           }
        } else {
            System.out.println("Suspended");
        }
   }
}

Solution

  • You use = incorrectly. In your example, if(isSuspended = true) {} means:

    boolean isSuspended = read.nextBoolean();
    //...
    isSuspended = true;
    
    if(isSuspended) {} // it will be always true
    

    To not assigned but check, you should use == instead.

    if (isSuspended == true) {
       // if true
    } else {
       // if false
    }
    

    or better:

    if (isSuspended) {
       // if true
    } else {
       // if false
    }
    

    P.S. I think you also mixed up the if cases.

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        boolean suspended = scan.nextBoolean();
        int ourScore = scan.nextInt();
        int theirScore = scan.nextInt();
    
        if (suspended)
            System.out.println("Suspended");
        else if (ourScore > theirScore)
            System.out.println("Won");
        else if (ourScore < theirScore)
            System.out.println("Lost");
        else
            System.out.println("Draw");
    }