Java Programming | If-else statements

Introduction

This is a tutorial for if-else statements in java. The program is given below that takes the number as input from user and prints it in words. The program makes use of if-else statements to decide the word of the number. The program is extendable. Go enjoy the program. Lets begin……….

Program for if-else statement in java.

//import Scanner as we require it.
import java.util.Scanner;

// the name of our class its public
public class If_else {
	//void main
		public static void main (String[] args)
		{
			//declare int
			int a;
			//print message
			System.out.println("Enter a number:");
			//Take input
			Scanner input = new Scanner(System.in);
			 a = input.nextInt();
			//if else statement
			 if(a==1)
				 System.out.println("One");
			 else
			 {
				 if(a==2)
					 System.out.println("Two");
				 else
				 {
					 if(a==3)
						 System.out.println("Three");
					 else
						 System.out.println("Error");
				 }
			 }
		}
}

Output

Enter a number:
2
Two

How it works

  1. The program prints the message to enter a number.
  2. The user enters a number.
  3. If-else statement decides the word and prints it.

Extending it

The program can be extended by using different numbers and alphabets .You can take the inputs and print it accordingly.

  • Note :- This is a basic concept in java programming and can be used in any program according to the concept of the program.

Explanation.

  1. Import the Scanner.
  2. Declare the class as public
  3. Add the void main function
  4. Add system.out.println() function with the message to enter a number.
  5. Declare input as Scanner.
  6. Take the inputs and save it in variables.
  7. Add a if-else statement.
  8. Add system.out.println() function to print the word.

At the end.

You learnt creating the Java program for If else statements. So now enjoy the program.

Please comment on the post and share it.
And like it if you liked.

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s