We are gonna write our very own first java program. In this article, while we uncover the program we will also learn a new concept called scanner class.
Before we head on to the programming part lets see what scanner class is.
Scanner class
A scanner class in java is nothing but a java util package utility to get the input from the user during runtime.
Syntax:
Scanner input = new Scanner(System.in);
Example
import java.util.Scanner;
public class Testing
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter A Number : ");
double numberOne = input.nextDouble();
System.out.print("Enter Operator: ");
String oP = input.next();
System.out.print("Enter Another Number : ");
double numberTwo = input.nextDouble();
if (oP.equals("+"))
System.out.println(numberOne+numberTwo);
else if (oP.equals("-"))
System.out.println(numberOne-numberTwo);
else if (oP.equals("*"))
System.out.println(numberOne*numberTwo);
else if (oP.equals("/"))
System.out.println(numberOne/numberTwo);
else if (oP.equals("%"))
System.out.println(numberOne%numberTwo);
else
System.out.println("Operator Not Found");
}
}
Output:
Enter A Number : 50
Enter Operator: /
Enter Another Number : 500
0.1
- Using the scanner class we have implemented a simple calculator program.
- As we know scanner class gets input from users.
- We are declaring it with object 'input'.
- Now we are giving a sysout to print some random sentences in this case I have done 'enter a number'.
- Now, the scanner class has many functions access by control+space there are many datatype functions under the scanner class.
- It will be in the form on nextDouble, next, etc.
- What it does is it fetches input from the user with that particular datatype and performs the rest of the action.
- You can verify them from the return type.
- Then I have used the if and elseif to do the necessary mathematical operations.
- If the oP is equal to the user input given as +,-,*,/ etc
- It will go through the if body and goes in the body of whatever the conditions satisfy based on user input.
- Thus you can also your mathematical functions like this as well too.
Related Content
Tags