50 likes | 73 Views
Chapter 4 Practice cont. Practice with nested loops. What will be the output of the following program segment: for (int i = 1; i <5; i++) { for (int j = 1; j < 5; j++) System.out.print (2*i+j + “ “); System.out.println(); } for (int i = 1; i <5; i++) {
E N D
Practice with nested loops • What will be the output of the following program segment: • for (int i = 1; i <5; i++) { for (int j = 1; j < 5; j++) System.out.print (2*i+j + “ “); System.out.println(); } • for (int i = 1; i <5; i++) { for (int j = 0; j <= i; j++) System.out.print (2*i+j + “ “); System.out.println(); }
Practice with File input and output • Write code that does the following: opens a file named MyName.txt, writes your name to the file, then closes the file. • Write code that does the following: opens a file named MyName.txt, reads the first line from the file and displays it, then closes the file. • A text file contains a sequence of integers, each in a separate line. Write code that reads this file and displays the sum of all numbers in the file.
Practice with Random class • Write code to display a random number in the interval [0, 1). • Write code to display a random number in the interval [0, 100). • Write code to display a random number in the interval [13, 19] (teenager) • Write code to display a random letter [A..Z] • Write code to display a string of 5 random letters.
Sample Problems • The sum S(n) is defined as:S(n) = 1 + ½ + 1/3 + … + 1/n.Write a program that reads a number M from keyboard, then displays the smallest value of n so that S(n) >= M. • Write a program to calculate the square root of a non-negative number n, using the while loop. Compare the result with the Math.sqrt() method. See instructions in class.