Page 225 - Introduction to Programming with Java: A Problem Solving Approach
P. 225
The symbol π is the ratio of a circle’s perimeter to its diameter, and the symbol E is the base of natural logarithms. The actual value of n! is always slightly smaller than the value given by this formula. For this exercise, write a Java code fragment that implements Stirling’s formula.
3. [after §5.3] Write a main method that asks the user for an angle, θ, in degrees, and prints out the values of sin(θ), cos(θ), and tan(θ).
Sample session:
Enter an angle in degrees: 30
sin(deg) = 0.49999999999999994
cos(deg) = 0.8660254037844387
tan(deg) = 0.5773502691896257
4. [after §5.3] Provide a statement that prints the length of the hypotenuse of a right triangle whose base is given by the variable base, and whose height is given by the variable height. In your statement, you must use the Math class’s hypot method. To learn about the hypot method, see Sun’s Java API Web site.
5. [after §5.3] Given the base-e log, you can always find the log to any other base, with the formula: logbase(x)
loge(x) / loge(base). For example, a computer scientist might be interested in how many bits are needed to express a given positive integer x in binary. In that case, the total number of bits required is log2(x), rounded up to the next higher integer. Write a Java statement that (1) calculates the number of bits required to store variable x’s value and (2) assigns that calculated value into an int variable named bits.
6. [after §5.6] In the following program skeleton, replace <Insert code here.> with your own code. Hint: Use the variables that are already declared for you (songs, searchText, foundIndex, and count). The resulting program should prompt the user for a search string and then display the number of occurrences of
the search string in a given list of songs. Study the sample session.
Apago PDF Enhancer
import java.util.Scanner;
public class CountSubstringOccurrences
{
public static void main(String[] args)
{
}
System.out.print("Enter search text: ");
searchText = stdIn.nextLine();
<Insert code here.>
System.out.println("Number of occurrences of \"" +
searchText + "\": " + count);
// end main
Scanner stdIn = new Scanner(System.in);
String songs =
"1. Green Day - American Idiot\n" +
"2. Jesus Jones - Right Here, Right Now\n" +
"3. Indigo Girls
"4. Peter Tosh -
String searchText;
int foundIndex;
int count = 0;
- Closer to Fine\n" +
Equal Rights\n";
// text that is searched for
// position of where text is found
// number of occurrences of search text
} // end class CountSubstringOccurrences
Exercises 191