Home > Software engineering >  how to make code print Suspended instead of won
how to make code print Suspended instead of won

Time:01-19

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");
        }
   }
}

CodePudding user response:

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");
}

CodePudding user response:

The problem is with the line:

if(isSuspended = true) {

It should be

if(isSuspended == true) {

or even:

if(isSuspended) {

isSuspended = true (with one =) assigns a new value to the variable isSuspended overriding whatever the user has entered.

In Java, those value assignments are treated like a value: isSuspended = true has the value true (so everywhere you could place a boolean like true or false, you can also put an expression like yourVariableName = true or myVariable = false, which also act like a boolean, but have the "side effect" of assigning a value to the variable).

If you want to compare a value for equality, you need to use == (or .equals(...) for Strings and other objects). If you want to check if a boolean is true, you don't even need == true, because the value of that comparison will be true or false in the end, which is just the value that the boolean you wanted to compare originally had.

  •  Tags:  
  • Related