Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 mixув 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");
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading