Showing posts with label Chpt3. Show all posts
Showing posts with label Chpt3. Show all posts

Saturday, February 13, 2016

Exercise 3.4

QUESTION

The purpose of this exercise is to take code from a previous exercise and encapsulate it in a method that takes parameters. You should start with a working solution to Exercise 2.2.

  1. Write a method called printAmerican that takes the day, date, month and year as parameters and that prints them in American format.
  2. Test your method by invoking it from main and passing appropriate arguments. The output should look something like this (except that the date might be different):
          Saturday, July 16, 2011

      3. Once you have debugged printAmerican, write another method called printEuropean that prints           the date in European format.

SOLUTION

public class ThinkJava3_Ex4 {
//Step 1
public static void printAmerican (String day, int date, String month, int year){
System.out.println(day+", "+month+" "+date+", "+year);
}
//Step 2
public static void main (String []args){
printAmerican("Sat", 2, "Jan", 2016);
//Step 4
printEuropean("Sat", 2, "Jan", 2016);
}
//Step 3
public static void printEuropean (String day, int date, String month, int year){
System.out.println(day+" "+date+" "+month+", "+year);
}
}

Exercise 3.3

QUESTION

The point of this exercise is to make sure you understand how to write and invoke methods that take parameters.

  1. Write the first line of a method named zool that takes three parameters: an int and two Strings.
  2. Write a line of code that invokes zool, passing as arguments the value 11, the name of your first pet, and the name of the street you grew up on.

SOLUTION


public class ThinkJava3_Ex3 {
//Step 1
public static void zool (int num, String pet, String street){
System.out.println(num);
System.out.println(pet);
System.out.println(street);
}
//Step 2
    public static void main (String[] args){
zool(11, "terrapin", "Woodlands");
}
}

Exercise 3.2

QUESTION

The point of this exercise is to practice reading code and to make sure that you understand the flow of execution through a program with multiple methods.


  1. What is the output of the following program? Be precise about where there are spaces and where there are newlines.
          HINT: Start by describing in words that ping and baffle do when they are invoked.

      2. Draw a stack diagram that shows the state of the program the first time ping is invoked.

public static void zoop() {
baffle();
System.out.print("You wugga ");
baffle();
}
public static void main(String[] args) {
System.out.print("No, I ");
zoop();
System.out.print("I ");
baffle();
}
public static void baffle() {
System.out.print("wug");
ping();
}
public static void ping() {
System.out.println(".");

}

SOLUTION


1. 
No, I wug.
You wugga wug.
I wug.