Код: Выделить всё
import java.util.Scanner;
public class Switch_Statement_Practice {
//Create a program that calculates the area or perimeter of a rectangle based on user input.
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int height;
int width;
char choice;
System.out.println("Do you want to calculate the area or perimeter of the rectangle? Type 'A' for area or 'P' for perimeter.");
choice = scnr.next().charAt(0); //.charAt(0) returns the character at the specified index position in a string. 0 returns the first characater in a given string.
switch (choice) {
case 'A' -> {
System.out.println("We are going to calculate the area.");
System.out.println("");
System.out.println("Enter the height.");
height = scnr.nextInt();
System.out.println("Enter the width");
width = scnr.nextInt();
System.out.println("The area is " + height * width + " units.");
break;
}
case 'P' -> {
System.out.println("We are going to calculate the perimeter.");
System.out.println("");
System.out.println("Enter the height.");
height = scnr.nextInt();
System.out.println("enter the width.");
width = scnr.nextInt();
System.out.println("The perimeter is: " + ((2 * height) + (2 * width)));
break;
}
default -> {
System.out.println("Invalid input. Please enter 'A' or 'P' (Without quotes).");
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/790 ... t-defaults
Мобильная версия