Solutions to Self-Study Exercises


[Page 96 (continued)]

Solution 2.1

The Java code fragment prints out the following:

The singing king. 


Solution 2.2

For the Riddle class (Fig. 2.12),

  1. The name of the class: Riddle

  2. The names of two instance variables: question, answer

  3. The names of three methods: Riddle(), getQuestion(), getAnswer()

Solution 2.3

For RiddleUser class (Fig. 2.15),

  1. The names of two Riddle instances: riddle1, riddle2

  2. All six method calls of the Riddle objects in the program:

    Riddle("What is black and white and red all over?",                             "An embarrassed zebra.") Riddle("What is black and white and read all over?",                                      "A newspaper.") riddle1.getQuestion() riddle1.getAnswer() riddle2.getQuestion() riddle2.getAnswer() 

  3. Qualified names: riddle1.getQuestion() and riddle1.getAnswer()

Solution 2.4

Definition of new instance variable in the Riddle class:

private String hint = "This riddle is too easy for a hint"; 



[Page 97]
Solution 2.5

The header for a getHint() method of the Riddle class, which should be a public method, is:

public String getHint(); 


Solution 2.6

The header for a setHint() method of the Riddle class is:

public void setHint(String aHint); 


The result type is void. Although the identifier used for the parameter is arbitrary, it is a good practice to make it descriptive by referring in some way to the hint instance variable.

Solution 2.7

The partial definition of the Student class is given below.

public class Student {  private String firstName;    private String lastName;    private int studentID;    public void setStudent(String fName, String lName, int anID);    public int getStudentID();    public String getStudentName(); } 


Solution 2.8

A main method that reads and squares a real number is given below.

public static void main(String[] args) {                                                      // Create Scanner object   Scanner sc = Scanner.create(System.in);   System.out.print("Input a real number:");            // Prompt   double realNum= sc.nextDouble();                     // Read a double   System.out.println(num + " squared = " + realNum*realNum); } // main() 





Java, Java, Java(c) Object-Orienting Problem Solving
Java, Java, Java, Object-Oriented Problem Solving (3rd Edition)
ISBN: 0131474340
EAN: 2147483647
Year: 2005
Pages: 275

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net