Computer Science Notes

Using Input with Scanner & Basic Operators: + - * / %

1. What Is the 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;

2. Creating a Scanner Object

To use the Scanner, we create an object:

Scanner input = new Scanner(System.in);

3. Common Scanner Methods

Method What It Reads
nextInt() Integer (whole number)
nextDouble() Decimal number
next() One word
nextLine() Full sentence (entire line)

4. Example: Getting User Input

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:

5. Basic Operators in Java

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

6. What Is the % (Modulus) Operator?

The % operator gives the remainder after division.

Examples:

10 % 3 = 1
8 % 2 = 0
7 % 2 = 1

Common uses:

7. Using Scanner with Math Operators

import 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));
    }
}

8. Important Rules

Integer Division Rule

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();

9. Real-World Examples

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 %

10. Key Vocabulary