CSCI 161 Exam #1, Spring 2024 ----------------------------- Problem 1: ---------- a) Instance variables (fields) can be used by any of the methods in a class, so their scope is the entire class. b) One advantage to returning rather than printing is that the returned value can be used elsewhere in a Java program. For example, in our last lab we called getDiameter() on Circle objects to see if they were of the right size to be drawn. If the method had printed the size rather than returning it we could not have used the size in our comparisons. c) The constructor's job is to set up an object's initial state. In other words, it's expected to assign values to each of the fields in the object. We've seen examples where it made sense to have several: One that made a "default" version of an object, for example, while another takes information from the user such as a speed or diameter. Having a copy constructor, as well, makes it easier to clone an existing object. Problem 2: ---------- public void mystery(int x) { if (x > 0) { limit = x; if (value >= limit) { value = 0; } } } a) If mystery is called on an object with limit=20 and value=15, and is passed 10 as an input, it would change the limit to 10 and the value to 0. b) The mystery method changes a NumberDisplay's limit to the specified value, x, as long as x is greater than 0. If its current value is greater than the new limit, the value is set to zero. (For example, if we tried to change a 24-hour clock's NumberDisplay to 12 hours, the value would also have to change if it was greater than 12.) Problem 3: ---------- Here's one way to write it: public boolean equals(NumberDisplay other) { if (value==other.value && limit==other.limit) { return true; } else { return false; } } You could also simplify it to this: public boolean equals(NumberDisplay other) { return (value==other.value && limit==other.limit); } Problem 4: ---------- Here's one way to write it, that checks if it's "very close" first: public void printStatus() { if (limit - value <= 2) { System.out.println("very close"); } else { if (limit - value <= 5) { System.out.println("pretty close"); } else { System.out.println("not close"); } } } You could also choose to check the cases in the other order: public void printStatus() { if (limit - value > 5) { System.out.println("not close"); } else { if (limit - value > 2) { System.out.println("pretty close"); } else { System.out.println("very close"); } } }