Java switch statement

Java Switch Statement


                                       In this tutorial i am going to show you how to work with java switch statement along with adding program. to do that follow these steps or simply watch my video.

YOUTUBE VIDEO OF JAVA SWITCH STATEMENT

  • First create a notepad file and open it
  • Give a name and Save the notepad file with .java (Ex: - decision.java)
  • Make sure the save as type is All Files
  • Then delete the notepad file if you want and edit the java file with a text editor
  • Paste or write down the code (code is below the tutorial) and make sure the class name is equal to the name that given to save the file.
  • Save the file and close it
  • open CMD (Command Prompt)
  • Set the JDK bin folder path coding by %path%;   (Ex:- set path=%path%;C:\Program Files\Java\jdk1.8.0_112\bin) and press enter
  • Set the directory where we saved the java file.
  • After that need to compile the java file to create class file. simple type - javac filename.java       (Ex:- javac decision.java)
  • To run the program type java filename  (Ex:- java decision)

To download JDK :- http://allinone-nsr.blogspot.com/p/jdk.html

The Code is :-



import java.util.Scanner; //imports scanner to get user input
class decision{ //class name
public static void main(String[] args){ //main method
System.out.println("Do you want to start the application (Type yes or no) :- "); //display this
Scanner begin = new Scanner(System.in); //create a new user input and name it begin
String choise=begin.next(); //declare a variable name choise and getting user input
switch (choise){ //checks choise variable
case "yes": //if choise equal to yes
System.out.println("Welcome to the adding machine"); //display this
break; //end statement
case "no": //if choise equal to no
System.out.println("Exiting"); //display this
System.exit(0); //system exits
break; //end statement
}  
System.out.println("Enter Number 1:- "); //display this
Scanner a = new Scanner(System.in); //create a new user input and name it a
int num1=a.nextInt(); //declare a variable name num1 and get the value of user input
System.out.println("Enter Number 2:- "); //display this
Scanner b = new Scanner(System.in); //create a new user input and name it a
int num2=b.nextInt(); //declare a variable name num1 and get the value of user input

int tot=num1+num2; //declare a variable call tot and assigning value num1 + num2 to tot

System.out.println("Total is: - "+tot);    //display total of num1 and num 2
}
}



No comments:

Post a Comment