Write a Java program that can calculate and print out the area of a square. The
ID: 3869872 • Letter: W
Question
Write a Java program that can calculate and print out the area of a square. The user enters data of the side and its measurement unit (“in” for inch, “ft” for feet, “cm” for centimeter, and “m” for meter) from the console. The program should check to be sure that the side is not negative and the measurement unit must be one among the listed-above units.
Important Notes:
Assumed that the user makes mistakes at most once for the side value and once for the measurement unit while entering the data, i.e. he/she enters the correct value the next time right after being warned.
Explanation / Answer
Below is your code. Let me know in comments if you have any issue: -
Area.java
import java.util.Scanner;
public class Area {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean done = false;
double side = 0;
String unit = "";
while (!done) {
System.out.print("Enter the side: ");
side = Double.parseDouble(in.next());
if (side < 0) {
System.out.println("Side cannot be negative.Please enter valid side.");
done = false;
} else {
done = true;
}
}
done = false;
while (!done) {
System.out.print("Enter the unit in/ft/cm/m: ");
unit = in.next();
if (!(unit.equalsIgnoreCase("in") || unit.equalsIgnoreCase("ft") || unit.equalsIgnoreCase("cm")
|| unit.equalsIgnoreCase("m"))) {
System.out.println("Please select valid unit.");
done = false;
} else {
done = true;
}
}
in.close();
System.out.println("Area of square = " + (side * side) + unit+"^2");
}
}
Sample Output:
Enter the side: -434
Side cannot be negative.Please enter valid side.
Enter the side: 5
Enter the unit in/ft/cm/m: jdn
Please select valid unit.
Enter the unit in/ft/cm/m: ft
Area of square = 25.0ft^2
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.