Today we are going to explain switch and while statements, but by using standard input, ouput and Scanner object that can be found in java.util package. Quite simple with practicing to know how switch statement works in some case. Let,s take code an example which asks the user to enter the number of the month then will show an output with its name.
Code is explained in it and I will clarify while and switch statements as follows:
We used while to tell the loop to be 12 times only if the number is invalid until it get the true value from switch statement which has true values consist of 1 to 12 with names, that is. We used break to termenate or in other meaning escape if this value is true.
/* This is our simple program, and we
* write description text here allows with names
* or any related details about the programe
* You_Java.java
*/
* write description text here allows with names
* or any related details about the programe
* You_Java.java
*/
import java.util.*; // Import statement
public class You_java // Class name
{
public static void main(String[]args)
{
int number; // Number entered by the user
Scanner changeToName = new Scanner(System.in); // Scanner has the name changeToName
System.out.print("Type number ");
number = changeToName.nextInt();
while (number > 12) // while to go into the loop
{
System.out.println("Impossible or invalid number ");
System.out.println("Enter number again ");
number = changeToName.nextInt();
}
switch (number) // switch statement to change number to name
{
case 1: System.out.println("JAN");break;
case 2: System.out.println("FEB");break;
case 3: System.out.println("MAR");break;
case 4: System.out.println("APR");break;
case 5: System.out.println("MAY");break; // Names of the months
case 6: System.out.println("JUN");break;
case 7: System.out.println("JUL");break;
case 8: System.out.println("AUG");break;
case 9: System.out.println("SEP");break;
case 10: System.out.println("OCT");break;
case 11: System.out.println("NOV");break;
case 12: System.out.println("DEC");break;
}
}
}
0 comments:
Post a Comment