stanford编程方法——习题答案(the art and science of java)——chapter07

    Chapter 07    The Object Memory mode
Review questions
-------------------------------------------------------------------------------
1. Define the following terms: bit, byte, and word.
Answer:
    bit:    can be in one of two possible states, 0, and 1
    byte:    8bits
    word:    32bits or 4 bytes
-------------------------------------------------------------------------------
2. What is the etymology of the word bit?
Answer:
    a unit of measurement of information (from binary + digit)
-------------------------------------------------------------------------------
3. How many bytes of memory are there in a 384MB machine?
Answer:
    384MB = 1024 * 1024 * 384 = 402653184B
-------------------------------------------------------------------------------
4. Convert each of the following decimal numbers to its hexadecimal equivalent:
a) 17
b) 256
c) 1729
d) 2766
Answer:
    a) 0x10
    b) 0x100
    c) 0x6c1
    d) 0xace
-------------------------------------------------------------------------------
5. Convert each of the following hexadecimal numbers to decimal:
a) 17
b) 64
c) CC
d) FAD
Answer:
    a) 23
    b) 100
    c) 204
    d) 4013   
-------------------------------------------------------------------------------
6. What is an address?
Answer:
    the byte's index position in the bytes' sequence   
-------------------------------------------------------------------------------
7. How many bytes does Java assign to a value of type int? How many bytes are
required for a double?
Answer:
    int:    4
    double: 8
-------------------------------------------------------------------------------
8. What are the three memory regions in which values can be stored in a Java
program?
Answer:
    memory devoted to the  program code and static data
    stack
    heap
-------------------------------------------------------------------------------
9. Using the example in section 7.2 as a model, trace the heap and stack
operations that occur in the execution of the following method:
    public void run() {
        Rational x = new Rational(4, 5);
        Rational y = new Rational(5, 2);
        Rational z = x.multiply(y).subtract(z);
        println(x + " x " + y + " - " + y + " = " + z);
    }
Which objects on the heap are garbage when the println statement is reached.
Answer:
    x, y
-------------------------------------------------------------------------------
10. True or false: When you pass a primitive data value from one method to
another, Java always copies that value into the frame of the method being
called.
Answer:
    true
-------------------------------------------------------------------------------
11. True or false: When you pass an object from one method to another, Java copies the data in that object into the new frame.
Answer:
    false
-------------------------------------------------------------------------------
12. Describe the two phases in a simple mark-and-sweep garbage collector.
Answer:
             (不理解题意)
-------------------------------------------------------------------------------
13. What is meant by the term wrapper class? What purpose do wrapper classes
serve?
Answer:
    encapsulate each of the primitive types in a full-fledeged object   
    to substitue the primitive types in some situation
-------------------------------------------------------------------------------
14. What methods can you use to convert between integers and the string
representations of those integers in a particular base?
Answer:
    pasrseInt(String str int radix)
    toString(int i, int radix)
-------------------------------------------------------------------------------
15. What property identifies a linked structure?
Answer:
    contains references to other objects
-------------------------------------------------------------------------------
16. Given that objects of a particular class require a certain amount of space
in memory, it is clear that an object in the heap could never physically
contain another object of that same class and still have room for additional
data. What can a Java programmer do to achieve the same effect?
Answer:
    Class p = new Class;
-------------------------------------------------------------------------------
17. What is a stub?
Answer:
    A simple implementation that you intend to replace later.   
-------------------------------------------------------------------------------
18. Why is important for Java to include the special value null? What does this value represent?
Answer:
    The constant null represents a reference to a nonexistent value and can be assigned to any variable that holds an object reference.

----------------------------------------------------------------------------------------------------------

1. Use the static methods Integer.parseInt and Integer.toString to write a
program that converts hexadecimal values into their decimal equivalents. Your
program should continue to read hexadecimal values until the user enters a 0. A
sample run of this program might look like this:

 

/* * File: HexToDecimalConverter.java * ---------------------------------- * The program that converts hexadecimal values into their decimal equivalents. */ import acm.program.*; import java.lang.*; public class HexToDecimalConverter extends ConsoleProgram { public void run() { printHeader(); while (true) { String hex = readLine("Enter a hexadecimal number: "); int dec = Integer.parseInt(hex, 16); if (dec == SENTINEL) { break; } println(hex + " hex = " + Integer.toString(dec) + " decimal"); } } private void printHeader() { println("This program converts hexadecimal to decimal."); println("Enter 0 to stop."); } private static final int SENTINEL = 0; }

 

 

2. The fact that the Integer.parseInt method makes it possible for a program to read
user input as a string and then convert it to an integer makes it possible to write
programs that use something other than an integer—such as a blank line—as a
188 The Art and Science of Java
sentinel to signal the end of the input. Rewrite the AverageList program from
exercise 4-6 so that it uses a blank line to mark the end of the input.

/* * File: AverageList.java * ----------------------- * The program reads in a list of integers representing exam scores * and then prints out the average. */ import acm.program.*; import java.lang.*; public class AverageList extends ConsoleProgram { public void run() { printHeader(); double sum = 0; int cnt = 0; while (true) { String line = readLine("please enter " + ++cnt + " num: "); if (line.length() == 0) break; sum += Integer.parseInt(line); } if(cnt != 0) println("the avarge is " + sum / cnt); else println("null"); } private void printHeader() { println("The program reads in a list of integers representing " + "exam scores and then prints out the average."); println("Enter values, one per line."); println("Enter Return to signal the end of the list."); } }

 

3. But don’t panic. Base 8 is just like base 10 really—if you’re missing two fingers.
—Tom Lehrer, “The New Math,” 1965
Rewrite the Math Quiz program from exercise 6-5 so that it poses its questions in
base 8 instead of base 10, as shown in the following sample run:

 

 

/* * File: The program rewrite the Math Quiz program from exercise 6-5 * so that it poses its questions in base 8 instead of base 10. */ import acm.util.*; import acm.program.*; public class MathQuiz extends ConsoleProgram { // the number of the questions. private static final int NUM_QUESTION = 5; private static final int MAX_NUM = 20; private static final int MIN_NUM = 0; private static final int TRY_NUM = 3; private static final String str[] = {"Correct!", "You got it!", "That's answer!"}; private static final int STR_SIZE = 3; public void run() { printHeader(); for (int i = 0; i < NUM_QUESTION; i++) { int answer = quetion( rgen.nextBoolean() ); int reply = myReadInt(""); for (int j = 1; j < TRY_NUM; j++) { if (reply == answer) { //println("That's the answer!"); println(str[rgen.nextInt(STR_SIZE)]); break; } else { reply = myReadInt("That's incorrect - try a different answer: "); } } if (reply != answer) { println("No, the answer is " + answer + "."); } } } private int myReadInt(String prompt){ String line = readLine(prompt); int reply = Integer.parseInt(line, 8); return reply; } private void printHeader(){ println("Welcome to the octal Math Quiz"); } // if sign is true, addition private int quetion(boolean sign) { int a, b, ret; if (sign) { a = rgen.nextInt(1, MAX_NUM); b = rgen.nextInt(1, MAX_NUM); ret = a + b; while (ret > MAX_NUM) { a = rgen.nextInt(1, MAX_NUM); b = rgen.nextInt(1, MAX_NUM); ret = a + b; } print("What is " + a + " + " + b + "? "); } else { a = rgen.nextInt(1, MAX_NUM); b = rgen.nextInt(1, MAX_NUM); ret = a - b; while (a - b < MIN_NUM) { a = rgen.nextInt(1, MAX_NUM); b = rgen.nextInt(1, MAX_NUM); ret = a - b; } print("What is " + a + " - " + b + "? "); } return ret; } /* Create an instance variable for the random number generator */ private RandomGenerator rgen = new RandomGenerator(); }

4. The Runtime class in the java.lang package includes a few simple methods that
may help you get a better sense of what Java’s garbage collector does. A Runtime
object maintains information about the state of the Java Virtual Machine. If you want
to look at that information, you can get the current runtime environment by calling
the static method getRuntime() and storing the result in a variable like this:
Runtime myRuntime = Runtime.getRuntime();
Once you have this variable, you can find out how much free memory is available by
calling
myRuntime.freeMemory();
Because memory sizes can be large, the value returned by freeMemory is a long
rather than an int and indicates the number of bytes available. You can also
explicitly trigger the garbage collector by calling
myRuntime.gc();
Write a program that allocates 10000 Rational objects without saving any of them
in variables so that they all become garbage. Once you’ve done so, measure the
amount of free memory before and after garbage collection and use the difference to
report how many bytes were freed, as shown in the following sample run:

import acm.util.*; import java.math.*; /** * The Rational class is used to represent rational numbers, which * are defined to be the quotient of two integers. */ public class Rational { /** * Creates a new Rational initialized to zero. */ public Rational() { this(0); } /** * Creates a new Rational from the integer argument. * @param n The initial value */ public Rational(int n) { this(n, 1); } /** * Creates a new Rational with the value x / y. * @param x The numerator of the rational number * @param y The denominator of the rational number */ public Rational(int x, int y) { if (y == 0) throw new ErrorException("Division by 0"); int g = gcd(Math.abs(x), Math.abs(y)); num = new BigInteger( "" + x / g); den = new BigInteger("" + Math.abs(y) / g); if (y < 0) num = num.negate(); } /** * Adds the rational number r to this one and returns the sum. * @param r The rational number to be added * @return The sum of the current number and r */ public Rational add(Rational r) { return new Rational(this.num.multiply(r.den).add(r.num.multiply(this.den)).intValue(), this.den.multiply(r.den).intValue()); } /** * Subtracts the rational number r from this one. * @param r The rational number to be subtracted * @return The result of subtracting r from the current number */ public Rational subtract(Rational r) { return new Rational(this.num.multiply(r.den).subtract(this.den.multiply(r.num)).intValue() , this.den.multiply(r.den).intValue()); } /** * Multiplies this number by the rational number r. * @param r The rational number used as a multiplier * @return The result of multiplying the current number by r */ public Rational multiply(Rational r) { return new Rational(this.num.multiply(r.num).intValue(), this.den.multiply(r.den).intValue() ); } /** * Divides this number by the rational number r. * @param r The rational number used as a divisor * @return The result of dividing the current number by r */ public Rational divide(Rational r) { return new Rational(this.num.multiply(r.den).intValue(), this.den.multiply(r.num).intValue()); } /** * Creates a string representation of this rational number. * @return The string representation of this rational number */ public String toString() { if ( 1 == den.intValue() ) { return " " + num; } else { return num + "/" + den; } } /** * Calculates the greatest common divisor using Euclid's algorithm. * @param x First integer * @param y Second integer * @return The greatest common divisor of x and y */ private int gcd(int x, int y) { int r = x % y; while (r != 0) { x = y; y = r; r = x % y; } return y; } /* Private instance variables */ //private int num; /* The numerator of this Rational */ //private int den; /* The denominator of this Rational */ private BigInteger num; /* The numerator of this Rational */ private BigInteger den; /* The denominator of this Rational */ }

/* * File: GCTest.java * ---------------------- * Write a program that allocates 10000 Rational objects without saving * any of them in variables so that they all become garbage. Once you’ve done so, * measure the amount of free memory before and after garbage collection and use * the difference to report how many bytes were freed. */ import acm.program.*; import java.lang.*; public class GCTest extends ConsoleProgram { private static final int ALLOC_NUM = 10000; public void run() { Runtime myRuntime = Runtime.getRuntime(); for (int i = 0; i < ALLOC_NUM; ++i) new Rational(); myRuntime.gc(); long fm = myRuntime.freeMemory(); printResult(ALLOC_NUM, fm); } private void printResult(long al, long fm) { println("Allocating " + al + " Rational objects"); println("Garbage collection freed " + fm + " bytes"); } }

你可能感兴趣的:(stanford,编程方法)