Scanner & Basic Operators: + - * / %Scanner Class?The Scanner class is used in Java to get input from the user through the keyboard. This allows programs to be interactive.
Before using Scanner, it must be imported:
import java.util.Scanner;
Scanner ObjectTo use the Scanner, we create an object:
Scanner input = new Scanner(System.in);
Scanner → class nameinput → object name (you can name it anything)System.in → tells Java to read from the keyboardScanner Methods| Method | What It Reads |
|---|---|
nextInt() |
Integer (whole number) |
nextDouble() |
Decimal number |
next() |
One word |
nextLine() |
Full sentence (entire line) |
import java.util.Scanner;
public class InputExample {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = input.nextInt();
System.out.println("You entered: " + age);
}
}
This program:
Java uses standard math operators:
| Operator | Name | Example | Result |
|---|---|---|---|
+ |
Addition | 5 + 3 |
8 |
- |
Subtraction | 5 - 3 |
2 |
* |
Multiplication | 5 * 3 |
15 |
/ |
Division | 10 / 2 |
5 |
% |
Modulus (remainder) | 10 % 3 |
1 |
% (Modulus) Operator?The % operator gives the remainder after division.
Examples:
10 % 3 = 1
8 % 2 = 0
7 % 2 = 1
Common uses:
Scanner with Math Operatorsimport java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter first number: ");
int num1 = input.nextInt();
System.out.print("Enter second number: ");
int num2 = input.nextInt();
System.out.println("Addition: " + (num1 + num2));
System.out.println("Subtraction: " + (num1 - num2));
System.out.println("Multiplication: " + (num1 * num2));
System.out.println("Division: " + (num1 / num2));
System.out.println("Remainder: " + (num1 % num2));
}
}
5 / 2 = 2 // NOT 2.5
Because both numbers are integers, the decimal part is dropped.
To get a decimal result, use at least one double:
double result = 5.0 / 2; // result is 2.5
Always close the Scanner when finished:
input.close();
| Scenario | Operator Used |
|---|---|
| Total cost of items | + |
| Calculating remaining money | - |
| Total price with quantity | * |
| Splitting a bill evenly | / |
| Checking if a number is even or odd | % |
+ or *.