Saturday, February 13, 2016

Exercise 4.5

Fermat's Last Theorem says that there are no integers a, b, and c such that

an+bcn

except in the case when n = 2.


Write a method named checkFermat that takes four integers as parameters—a, b, c and n—and that checks to see if Fermat’s theorem holds. If n is greater than 2 and it turns out to be true that an+bn = cn, the program should print than 2 and it turns out to be true that an+bn = cn, the program should print 

“Holy smokes, Fermat was wrong!” Otherwise the program should print “No, that doesn’t work.”


You should assume that there is a method named raiseToPow that takes two integers as arguments and that raises the first argument to the power of the second. For example:
     int x = raiseToPow(2,3);
would assign the value 8 to x, because 23 = 8.

Exercise 4.4

QUESTION

What is the output of the following program?

public class Narf {

     public static void zoop(String fred, int bob) {
          System.out.println(fred);
          if (bob == 5 ) {
               ping ("not ");
          } else {
               System.out.println("!");
          }
     }
   
     public static void main(String[] args) {
          int bizz = 5;
          int buzz = 2;
          zoop("just for", bizz);
          clink(2*buzz);
     }

     public static void clink(int fork) {
          System.out.print(It's ");
          zoop("breakfast ", fork) ;
     }

     public static void ping(String strangStrung) {
          System.out.println("any " + strangStrung + "more ");
     }
}

SOLUTION

just for
any not more
It's breakfast
!

Exercise 4.3

QUESTION

The first verse of the song “99 Bottles of Beer” is:

99 bottles of beer on the wall, 99 bottles of beer, ya’ take one down, ya’ pass it around, 98 bottles of beer on the wall.

Subsequent verses are identical except that the number of bottles gets smaller by one in each verse, until the last verse:

No bottles of beer on the wall, no bottles of beer, ya’ can’t take one down, ya’ can’t pass it around, ’cause there are no more bottles of beer on the wall!

And then the song(finally) ends.

Write a program that prints the entire lyrics of “99 Bottles of Beer.” Your program should include a recursive method that does the hard part, but you might want to write additional methods to separate the major functions of the program.

As you develop your code, test it with a small number of verses, like “3 Bottles of Beer.”
The purpose of this exercise is to take a problem and break it into smaller problems, and to solve the smaller problems by writing simple methods.

SOLUTION

public class ThinkJava4_Ex3 {
public static void BeerSong (int beer){
if (beer>0){
System.out.print(beer+" bottles of beer on the wall, ");
System.out.print(beer+" bottles of beer, ya' take one down, ya' pass it around, ");
System.out.println(beer-1+" bottles of beer on the wall.");
BeerSong(beer-1);
} else {
System.out.println("No bottles of beer on the wall, no bottles of beer, ya' can't take one down, ya' can't pass it around, 'cause there are no more bottles of beer on the wall!");
}
}
public static void main (String[]args){
BeerSong (99);
}
}

Exercise 4.2

This exercise reviews the flow of execution through a program with multiple methods. Read the following code and answer the questions below.

public class Buzz {

public static void baffle(String blimp) {
System.out.println(blimp);
zippo("ping", -5);
}

public static void zippo(String quince, int flag) {
if (flag < 0) {
System.out.println(quince + " zoop");
}
else {
System.out.println("ik");
baffle(quince);
System.out.println(
"boo-wa-ha-ha");
}
}

public static void main(String[] args) {
zippo("rattle", 13);
}
}

  1. Write the number 1 next to the first statement of this program that will be executed. Be careful to distinguish things that are statements from things that are not.
  2. Write the number 2 next to the second statement, and so on until the end of the program. If a statement is executed more than once, it might end up with more than one number next to it.
  3. What is the value of the parameter blimp when baffle gets invoked?
  4.  What is the output of this program?

SOLUTION

1.
1 System.out.println("ik");

2.
2 System.out.println(blimp);
3 System.out.println(quince + " zoop");
4 System.out.println("boo-wa-ha-ha");

3.Value of parameter blimp when baffle gets invoked is rattle.

4. 
ik
rattle
ping zoop
boo-wa-ha-ha


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. 

Exercise 2.3

QUESTION

  1. Create a new program called Time.java. From now on, I won’t remind you to start with a small, working program, but you should.
  2. Following the example in Section 2.6, create variables named hour, minute and second, and assign them values that are roughly the current time. Use a 24-hour clock, so that at 2pm the value of hour is 14.
  3. Make the program calculate and print the number of seconds since midnight.
  4. Make the program calculate and print the number of seconds remaining in the day.
  5. Make the program calculate and print the percentage of the day that has passed.
  6. Change the values of hour, minute and second to reflect the current time (I assume that some time has elapsed), and check to make sure that the program works correctly with different values.
The point of this exercise is to use some of the arithmetic operations, and to start thinking about compound entities like the time of day that that are represented with multiple values. Also, you might run into problems computing percentages with ints, which is the motivation for floating point numbers in the next chapter.


HINT: you may want to use additional variables to hold values temporarily
during the computation. Variables like this, that are used in a computation
but never printed, are sometimes called intermediate or temporary variables.

SOLUTION

public class ThinkJava2_Ex3 {
public static void main (String[]args) {
//Step 2
int hour, minute, second;
hour = 16;
minute = 24;
second = 39;
//For checking
System.out.println(hour+":"+minute+":"+second);
//Step 3
int secSinceMidNite;
secSinceMidNite = ((hour*60)+minute)*60 + second;
System.out.println("Seconds since midnight = "+secSinceMidNite);
//Step 4
int secRemainingInDay, totalSecInDay;
totalSecInDay = 24*60*60;
secRemainingInDay = totalSecInDay - secSinceMidNite;
System.out.println("Seconds remaining in day = "+secRemainingInDay);
//Step 5
int percentOfDayPassed;
percentOfDayPassed = (secSinceMidNite*100)/totalSecInDay;
System.out.println("Percentage of day passed = " +percentOfDayPassed+"%");
/*Step 6
Change values of hour, minute, second and run again
*/
}
}

Exercise 2.2


QUESTION

  1. Create a new program named Date.java. Copy or type in something like the “Hello, World” program and make sure you can compile and run it.
  2. Following the example in Section 2.4, write a program that creates variables named day, date, month and year. day will contain the day of the week and date will contain the day of the month. What type is each variable? Assign values to those variables that represent today’s date.
  3. Print the value of each variable on a line by itself. This is an intermediate step that is useful for checking that everything is working so far.
  4. Modify the program so that it prints the date in standard American form: Saturday, July 16, 2011.
  5. Modify the program again so that the total output is:
American format:
Saturday, July 16, 2011
European format:
Saturday 16 July, 2011

The point of this exercise is to use string concatenation to display values with different types (int and String), and to practice developing programs gradually by adding a few statements at a time.

SOLUTION

public class ThinkJava2_Ex2 {
public static void main (String [] args){
String day = "Sat";
int date = 2;
String month = "Jan";
int year = 2016;
//Step 3
System.out.println(day);
System.out.println(date);
System.out.println(month);
System.out.println(year);
//Step 4
System.out.println(day+", "+month+" "+date+", "+year);
//Step 5
System.out.println("American format:");
System.out.println(day+", "+month+" "+date+", "+year);
System.out.println("Eurpoean format:");
System.out.println(day+" "+date+" "+month+", "+year);
}
}

Exercise 2.1

QUESTION

If you are using this book in a class, you might enjoy this exercise: find a partner and play “Stump the Chump”:
Start with a program that compiles and runs correctly. One player turns away while the other player adds an error to the program. Then the first player tries to find and fix the error. You get two points if you find the error without compiling the program, one point if you find it using the compiler, and your opponent gets a point if you don’t find it.

SOLUTION

I need a person for this. -_-"
So, no solution. 

Exercise 1.3

QUESTION

It is a good idea to commit as many errors as you can think of, so that you see what error messages the compiler produces. Sometimes the compiler tells you exactly what is wrong, and all you have to do is fix it. But sometimes the error messages are misleading. You will develop a sense for when you can trust the compiler and when you have to figure things out yourself.

  1. Remove one of the open squiggly-braces.
  2. Remove one of the close squiggly-braces.
  3. Instead of main, write mian,
  4. Remove the word static.
  5. Remove the word public.
  6. Remove the word System.
  7. Replace println with Println.
  8. Replace println with print. This one is tricky because it is a logic error, not a syntax error. The statement System.out.print is legal, but it may or may not do what you expect.
  9. Delete one of the parentheses. Add an extra one.

SOLUTION

  1. Syntax error
  2. Syntax error
  3. Error: Main method not found in class
  4. Error: Main method is not static in class
  5. Error: Main method not found in class
  6. out cannot be resolved
  7. Method Println(String) is undefined for the type PrintStream
  8. Output of 2 sentences are on the same line
  9. Syntax error, Syntax error

Exercise 1.2

QUESTION


Before you do anything else, find out how to compile and run a Java program in your environment. Some environments provide sample program similar to the example in Section 1.5.
  1. Type in the “Hello, world” program, then compile and run it.
  2. Add a print statement that prints a second message after the “Hello, world!”. Something witty like, “How are you?” Compile and run the program again.
  3.  Add a comment to the program (anywhere), recompile, and run it again. The new comment should not affect the result.
The exercise may seem trivial, but it is the starting place for many of the programs we will work with. To debug with confidence, you have to have confidence in your programming environment. In some environments, it is easy to lose track of which program is executing, and you might find yourself trying to debug one program while you are accidentally running another. Adding (and changing) print statements is a simple way to be sure that the program you are looking at is the program you are running.


SOLUTION


public class ThinkJava1_Ex2 {
 public static void main (String[]args){
System.out.println("Hello, world");
System.out.println("How are you?");
}
}

//This is a comment.

Monday, February 8, 2016

Exercise 1.1

QUESTION

Computer scientists have the annoying habit of using common English words to mean something other than their common English meaning. For example, in English, statements and comments are the same thing, but
in programs they are different.


The glossary at the end of each chapter is intended to highlight words and phrases that have special meanings in computer science. When you see familiar words, don’t assume that you know what they mean!

1. In computer jargon, what’s the difference between a statement and a
comment?
2. What does it mean to say that a program is portable?
3. What is an executable?


SOLUTION

1. 
A statement is a part of a program that specifies a computation.abstract
A comment is a part of a program that contains information about the program, but that has no effect when the program runs

2.
A program is portable when it can be run on more than one kind of computer.

3.
An executable is another name for object code that is ready to run.