-
Do While loop error
Good evening everyone. I'm trying to figure out where the error in my program is. I'm making a program that calculates the area of a shape, and it is supposed to run in a Do-While loop as long as the user inputs a "Y". If the user inputs an "N" the program is supposed to terminate. The program compiles, but there is a logic error that causes the program to terminate when it asks the user if they would like to compute another area.
Here's what the program looks like:
/*
Purpose: This program computes the area of a square with a loop
*/
import java.util.Scanner;
import java.text.*;
public class Square
{
/** Main method */
public static void main (String[] args)
{
// Define Constants
final String AREA_FORMAT = "#,###.000";
// Define Variables
double width;
double area;
Scanner input = new Scanner(System.in);
DecimalFormat dfArea = new DecimalFormat(AREA_FORMAT);
char response = 'Y';
// Assign a value to the height and width
do{
System.out.print("Enter the width and height of a perfect square: ");
width = input.nextDouble();
// Check user input
if (width > 0)
{
// Compute area using the width x height formula
area = width * width;
// Display results
// Using a combination of DecimalFormat Class and printf formatters
System.out.printf("The area of a square is computed by the following formula:\n\tArea = width x height");
System.out.println("\nBy subtituting in the value(s) that you entered, the formula looks like:");
System.out.printf("\tArea = %s x %s ", dfArea.format(width), dfArea.format(width));
System.out.printf("\n\tArea = %s\n", dfArea.format(area));
}
else
// Print out Error Message
System.out.printf("The area of a square can only be calculated by using a width or height value greater than 0.\nYou entered \"%s\" for the width.\n", dfArea.format(width));
do
{
System.out.print("Would you like to play again? (Y or N)");
response = (char)input.nextInt();
switch (response)
{
case 'Y': response = 'Y';
break;
case 'y': response = 'Y';
break;
case 'N': response = 'N';
break;
case 'n': response = 'N';
break;
default: System.out.print("You have made an invalid entry");
}
}
while (response == 'Y');
}while (response != 'N');
}
}
-
Try response = input.next().charAt(0); instead of response = (char)input.nextInt();
And I think you are looking for
while (response != 'Y' && response != 'N')
for the condition of the inner do-while loop ?!