Page 224 - Introduction to Programming with Java: A Problem Solving Approach
P. 224
190 Chapter 5 Using Pre-Built Methods
§5.4 Wrapper Classes for Primitive Types
3. Provide a statement that assigns positive infinity into a double variable named num.
4. Provide a statement that converts a string variable named s to a long and assigns the result to a long
variable named num.
5. Provide a statement that converts an int variable named num to a string and assigns the result to a
String variable named numStr. Use a wrapper class method.
§5.5 CharacterClass
6. What does the following code fragment print? System.out.println(Character.isDigit('#'));
System.out.println(Character.isWhitespace('\t'));
System.out.println(Character.toLowerCase('B'));
§5.6 StringMethods 7. Given this declaration:6
String snyder = "Stick together.\nLearn the flowers.\nGo light.";
Write a Java statement that finds the index of the letter ‘G’ and prints everything in snyder from that point on.Inotherwords,itprintsGo light.
§5.7 Formatted Output with the printf Method
8. Write a format string that handles the display of three data items in three columns. The first column should
be 20 spaces wide, and it should print a left-aligned string. The second column should be 10 spaces wide, and it should print a right-aligned integer. The third column should be 16 spaces wide, and it should print
Apago PDF Enhancer
a right-aligned floating-point number in scientific format with 6 decimal places. Your format string should
cause the screen’s cursor to move to the next line after printing the third data item.
9. Provide a format specifier that handles the display of a floating-point data item. It should print a rounded
version of the data item with no decimal places. It should insert grouping separators, and it should use parentheses if the number is negative.
§5.8 Problem Solving with Random Numbers (Optional)
10. Write a Java statement that prints a random number for the total number of dots on a roll of a pair of dice. 11. Write a program that prints five random boolean values with the seed, 123L. Then display those values.
Exercises
1. [after §5.3] Write a statement that computes and prints the cube root of a double variable named number. [Hint: look for an appropriate method in Sun’s documentation of the Math class.]
2. [after §5.3] In probability calculations, we frequently need to compute the value of the factorial of some number n. The factorial of a number n (designated n!) is given by the formula,
n! ← n * (n-1) * (n-2) * ... * 3 * 2 * 1.
When n is a very large number, this is a time-consuming calculation. Fortunately there is a handy formula, called Stirling’s Formula, which gives a very good approximation to n! whenever n is large. Stirling’s formula says:
n! ≈ (1 + 1/(12n -1)) * sqrt(2nπ) * (n/E)n
6 Gary Snyder, “For the Children” in Turtle Island, New Directions (1974).