• Log in or sign up for an account here: https://www.sythe.org/login

Homework Help

Kuwi

Member

Banned
Joined
Jul 31, 2007
Sythe Gold
0
Messages
35
What is wrong with the following code fragment? Rewrite it so that it produces correct output.

Code:
if (total == MAX)
     if (total < sum)
          System.out.println("total == MAX and is < sum.");
else
     System.out.println("total is not equal to MAX");

I'm new to programming and I'm not very good with logic.
 
Code:
if (total == MAX)
     if (total < sum)
          System.out.println("total == "
                                        + MAX +  " and is < " + sum);
else
     System.out.println("total is not equal to MAX");

I think is what you are looking for possibly....
 
brackets are messed up... the ELSE applies to the second IF, not the first (as it should).

Current
Code:
if (total == MAX)
{
     if (total < sum)
     {
          System.out.println("total == MAX and is < sum.");
     }
     else
     {
          System.out.println("total is not equal to MAX");
     }
}


Correct
Code:
if (total == MAX)
{
     if (total < sum)
     {
          System.out.println("total == MAX and is < sum.");
     }
}
else
{
     System.out.println("total is not equal to MAX");
}

You can also change the error message, but I don't think that's what they're looking for.
 
Code:
if (total == MAX && total < sum)
          System.out.println("total == MAX and is < sum.");
else
     System.out.println("total is not equal to MAX");
 
Going off of Nullware's post


This will compare the values and then also print the values out.

Code:
if (total == MAX && total < sum)
          System.out.println("total = " + MAX " and is < " + sum  +".");
else
     System.out.println("Total is not equal to MAX");
 
Back
Top