Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- class MonthPrinter {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- int number = Integer.parseInt(scanner.nextLine());
- String result = "";
- switch (number) {
- case 1:
- result = "January";
- break;
- case 2:
- result = "February";
- break;
- case 3:
- result = "March";
- break;
- case 4:
- result = "April";
- break;
- case 5:
- result = "May";
- break;
- case 6:
- result = "June";
- break;
- case 7:
- result = "July";
- break;
- case 8:
- result = "August";
- break;
- case 9:
- result = "September";
- break;
- case 10:
- result = "October";
- break;
- case 11:
- result = "November";
- break;
- case 12:
- result = "December";
- break;
- default:
- result = "Error!";
- break;
- }
- System.out.println(result);
- }
- }
- Solution with new switch pattern(Java 21):
- import java.util.Scanner;
- class MonthPrinter {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- int number = Integer.parseInt(scanner.nextLine());
- String result = switch (number) {
- case 1 -> "January";
- case 2 -> "February";
- case 3 -> "March";
- case 4 -> "April";
- case 5 -> "May";
- case 6 -> "June";
- case 7 -> "July";
- case 8 -> "August";
- case 9 -> "September";
- case 10 -> "October";
- case 11 -> "November";
- case 12 -> "December";
- default -> "Error!";
- };
- System.out.println(result);
- }
- }
- Solution with ternary operator:
- import java.util.Scanner;
- class MonthPrinter {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- int number = Integer.parseInt(scanner.nextLine());
- String result =
- number == 1 ? "January" :
- number == 2 ? "February" :
- number == 3 ? "March" :
- number == 4 ? "April" :
- number == 5 ? "May" :
- number == 6 ? "June" :
- number == 7 ? "July" :
- number == 8 ? "August" :
- number == 9 ? "September" :
- number == 10 ? "October" :
- number == 11 ? "November" :
- number == 12 ? "December" : "Error!";
- System.out.println(result);
- }
- }
- Solution with array and ternary operator:
- import java.util.Scanner;
- class MonthPrinter {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- int number = Integer.parseInt(scanner.nextLine());
- String months[] = {
- "Error!",
- "January",
- "February",
- "March",
- "April",
- "May",
- "June",
- "July",
- "August",
- "September",
- "October",
- "November",
- "December"
- };
- String result = number > 0 && number < 13 ? months[number] : months[0];
- System.out.println(result);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement