Page 162 - Introduction to Programming with Java: A Problem Solving Approach
P. 162

                 128
Chapter 4 Control Statements
 /***************************************************************
*
FloorSpace.java
Dean & Dean
This program calculates total floor space in a house.
****************************************************************/
*
*
*
import java.util.Scanner;
public class FloorSpace
{
}
// end class FloorSpace
public static void main(String[] args)
{
}
// end main
Scanner stdIn = new Scanner(System.in);
double length, width;
}
// room dimensions
// house's total floor space
// user's y/n response
System.out.print("Enter the length: ");
length = stdIn.nextDouble();
System.out.print("Enter the width: ");
double floorSpace = 0;
char response;
do
{
stdIn.AnepxtaDogubole()P;DF Enhancer floorSpace += length * width;
System.out.print("Any more rooms? (y/n): ");
response = stdIn.next().charAt(0);
while (response == 'y' || response == 'Y');
width
=
System.out.println("Total floor space is " + floorSpace);
Figure 4.13 Using a do loop to calculate total floor space
For another example, suppose you want to find the factorial of a user-entered number, like this:
Sample session:
Enter a whole number: 4
4! = 24
For 4 factorial, you need to multiply the values 1 through 4: 1 􏰇 2 􏰇 3 􏰇 4 􏰅 24. The three 􏰇’s in- dicate that three multiplications are necessary. So 4 factorial requires three loop iterations. For the general case, where you need to find the factorial for a user-entered number, store the user-entered number in a count variable. Then multiply the values 1 through count like this:
1 * 2 * 3 * . . . * count count - 1 number of *’s
 ⎧ ⎪ ⎨ ⎪ ⎪ ⎩



















































   160   161   162   163   164