reset password
Author Message
rabbott
Posts: 1649
Posted 16:57 Feb 03, 2014 |

The quiz scores were much better this week.

10 - 2

9 - 9

8 - 6

7 - 4

2 - 1

 

Question 9 was the only one with fewer than 18 correct answers (out of 22).

Which of the following will be false if String country is neither "China" nor "Denmark"?

  • !country.equals("China") || !country.equals("Denmark") 7
  • !( country.equals("China") || country.equals("Denmark") ) 3
  • !( country.equals("China") && country.equals("Denmark") ) 6
  • country.equals("China") || country.equals("Denmark") 6

The answers evaluate as follows.

  • !country.equals("China") || !country.equals("Denmark") => !false || !false => true || true => true
  • !( country.equals("China") || country.equals("Denmark") ) => !( false || false ) => !(false) => true
  • !( country.equals("China") && country.equals("Denmark") ) => !( false && false ) => !( false ) => true
  • false || false => false    <== the correct answer

 

Last edited by rabbott at 16:59 Feb 03, 2014.
ytsai8
Posts: 47
Posted 19:25 Feb 03, 2014 |

For number 7, I simply plugged the method into BlueJ and got the answer, but when I tried to understand the question it is really confusing. Is it okay to post the explanation for this question too?

rabbott
Posts: 1649
Posted 22:27 Feb 03, 2014 |

I was going to reply that it would be fine for you to post the explanation, but I guess you want me to post it.

What is the output of the following code snippet?

 

  1. boolean attendance = false;
  2. String str = "Unknown";
  3. attendance = !(attendance);
  4. if (!attendance) str = "False";
  5. if (attendance) attendance = false;
  6. if (attendance) str = "True";
  7. else str = "Maybe";
  8. System.out.println(str);
 False
 True
 Unknown
 Maybe
 
I've numbered the lines for convenience. Here is the value of attendance and str after each line.

 

  attendance str
1 false <undeclared>
2 false "Unknown"
3 true "Unknown"
4 true "Unknown"
5 false "Unknown"
6 false "Unknown"
7 false "Maybe"
 
You could get the same information by inserting
System.out.printf("attendance: %s; str: %s\n", attendance, str);
after each line. (If you put it in after line 1 take out the reference to str. If you put it in after line 6, enclose str = true; and the added line in braces.)
Last edited by rabbott at 20:53 Feb 06, 2014.
rabbott
Posts: 1649
Posted 22:36 Feb 03, 2014 |

The preceding two questions can be confusing. There is no magic way to disentangle those boolean expressions and have the right answer jump out at you. You just have to work it out step by step.

Last edited by rabbott at 22:37 Feb 03, 2014.