Explanation
This Java program demonstrates how to take a numerical input from the user representing a day of the week (from 1 to 7) and then display the corresponding day's name. It utilizes the Scanner class to read user input and a switch statement to efficiently handle multiple possible conditions based on the entered number.
Here's a step-by-step breakdown of the logic:
- Import Scanner: The line
import java.util.Scanner;brings in theScannerclass, which is essential for reading input from the user (like typing on the keyboard). - Class and Main Method: The code is enclosed within a class named
prog13, and the execution begins in themainmethod, which is the entry point of any Java program. - Create Scanner Object:
Scanner input = new Scanner(System.in);creates an object of theScannerclass, namedinput. This object is configured to read data fromSystem.in, which represents the standard input stream (usually the keyboard). - Prompt User:
System.out.print("Enter a number to get Day of the Week: ");displays a message on the console, asking the user to enter a number.System.out.printis used instead ofprintlnso that the cursor stays on the same line after the prompt, allowing the user to type their input directly after the message. - Read User Input:
int num = input.nextInt();reads the integer value entered by the user from the console and stores it in an integer variable namednum. - Switch Statement: The
switch(num)statement checks the value stored in thenumvariable. It then compares this value against a series ofcaselabels.- Cases 1-7: If
nummatches any of thecasevalues (1 through 7), the correspondingSystem.out.println()statement is executed, printing the name of the day. For example, ifnumis 3, it will print "Day of the week is Wednesday". - Break Statement: The
break;statement after eachcaseis crucial. It terminates theswitchstatement immediately after a matchingcaseis found and its code is executed. Withoutbreak, the program would continue to execute the code in the subsequentcaselabels (this is called "fall-through"), which is usually not the desired behavior in this scenario. - Default Case: The
default:case acts as a catch-all. If the value ofnumdoes not match any of the specifiedcasevalues (1 through 7), the code within thedefaultblock is executed, printing "Invalid number".
- Cases 1-7: If
- Close Scanner:
input.close();closes theScannerobject. This is good practice as it releases the system resources associated with the scanner.