Integer Division, Modulus & Scanner
Interactive programs that read input and do math
Quick check before you start: Do you know the four core primitive types? Can you declare and initialize variables?
Practice this topic: Lab 1 exercises on user input
After this lesson, you will be able to:
- Use integer division and explain how truncation differs from rounding
- Apply the modulus operator (%) to solve real-world problems
- Read user input using the Scanner class
- Avoid the notorious nextInt()/nextLine() buffer trap
Interactive Programs
So far, every program you have written uses hardcoded values. The width is always 5.0, the name is always “Alice”, the age is always 25. Real programs respond to their users.
In this lesson, your programs become interactive: the user types input, your program stores it in a variable, processes it, and displays a result.
We also master two arithmetic operations — integer division and modulus — that appear in nearly every program you will write.
From CSCD 110: In Python, you used
input()which always returns a string, and you converted withint(). Java’s Scanner provides type-specific methods:nextLine()returns a String,nextInt()returns an int.
Integer Division: Truncation, Not Rounding
When both operands of / are integers, Java performs integer division. It divides and then truncates — throws away the decimal part. It does not round.
public class IntDiv {
public static void main(String[] args) {
System.out.println(7 / 2); // 3 (not 3.5, not 4)
System.out.println(10 / 3); // 3 (not 3.333)
System.out.println(100 / 7); // 14 (not 14.285)
System.out.println(1 / 3); // 0 (not 0.333)
System.out.println(-7 / 2); // -3 (truncates toward zero)
}
}
Key insight: Integer division truncates toward zero. For positive numbers, truncation and flooring give the same result. For negative numbers, they differ:
-7 / 2in Java is-3(truncation), while Python’s-7 // 2is-4(flooring).
Getting the “Real” Answer
If you want the decimal result, at least one operand must be floating-point:
public class Division {
public static void main(String[] args) {
// Option 1: Use a decimal literal
System.out.println(7.0 / 2); // 3.5
// Option 2: Use decimal on the other side
System.out.println(7 / 2.0); // 3.5
// Option 3: Cast one operand (most common in practice)
int total = 45;
int count = 10;
double average = (double) total / count; // 4.5
System.out.println(average);
}
}
Option 3 is the most common because you usually have variables, not literals.
Watch out: Parentheses placement matters with casts:
(double)(a / b)— integer division first (3), then cast to 3.0 (wrong!)(double) a / b— cast first (7.0), then divide to get 3.5 (correct!)
The Modulus Operator: %
The modulus operator % gives the remainder after integer division:
public class Modulus {
public static void main(String[] args) {
System.out.println(7 % 2); // 1 (7 = 2*3 + 1)
System.out.println(10 % 3); // 1 (10 = 3*3 + 1)
System.out.println(15 % 5); // 0 (15 = 5*3 + 0)
System.out.println(4 % 7); // 4 (4 = 7*0 + 4)
System.out.println(100 % 10); // 0
}
}
The relationship: dividend == (dividend / divisor) * divisor + (dividend % divisor)
Real-World Uses of Modulus
- Even/odd detection:
n % 2 == 0means even - Wrap-around:
minutes % 60for clock math - Digit extraction:
number % 10gets the last digit - Looping within bounds:
i % ncycles through 0 to n-1
17 / 5?17 % 5?Reading User Input: The Scanner Class
Java uses the Scanner class to read input from the user:
import java.util.Scanner;
public class Input {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.print("Enter your age: ");
int age = scanner.nextInt();
System.out.println("Hello, " + name + "!");
System.out.println("You are " + age + " years old.");
}
}
Common Scanner Methods
| Method | Returns | Example |
|---|---|---|
nextLine() |
String | Reads entire line |
next() |
String | Reads next word |
nextInt() |
int | Reads next integer |
nextDouble() |
double | Reads next double |
nextBoolean() |
boolean | Reads next boolean |
The Buffer Trap: nextInt() vs nextLine()
This is the most infamous bug in Java. Watch closely:
import java.util.Scanner;
public class BufferTrap {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = scanner.nextInt(); // User types "25" and presses Enter
System.out.print("Enter your name: ");
String name = scanner.nextLine(); // BUG: reads empty string!
System.out.println("Age: " + age);
System.out.println("Name: " + name);
}
}
What happens: When the user types “25” and presses Enter, the input buffer contains “25\n” (the number plus the newline character). nextInt() reads “25” but leaves the newline in the buffer. Then nextLine() immediately reads that leftover newline — an empty string.
The Fix
Option 1: Use nextLine() for everything and convert:
String ageStr = scanner.nextLine();
int age = Integer.parseInt(ageStr);
Option 2: Add a dummy nextLine() after nextInt():
int age = scanner.nextInt();
scanner.nextLine(); // Consume the leftover newline
String name = scanner.nextLine(); // Now this works
The trick: For this course, always use
nextLine()and convert when you need numbers. It is safer and avoids the buffer trap entirely.
Putting It Together: Interactive Calculator
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number: ");
int num1 = Integer.parseInt(scanner.nextLine());
System.out.print("Enter second number: ");
int num2 = Integer.parseInt(scanner.nextLine());
System.out.println("Sum: " + (num1 + num2));
System.out.println("Difference: " + (num1 - num2));
System.out.println("Product: " + (num1 * num2));
System.out.println("Quotient: " + (num1 / num2));
System.out.println("Remainder: " + (num1 % num2));
}
}
Example run:
Enter first number: 17
Enter second number: 5
Sum: 22
Difference: 12
Product: 85
Quotient: 3
Remainder: 2
What you learned
- Integer division truncates toward zero. Both operands must be floating-point for decimal results.
- Modulus (%) gives the remainder. Useful for even/odd, digit extraction, and cyclic patterns.
- Scanner reads user input. Use
nextLine()and convert for safety. - The buffer trap:
nextInt()leaves a newline. Always usenextLine()and parse, or consume the newline afternextInt().
What Comes Next
| Week 2 dives deeper into expressions and operators. You will learn boolean logic (&&, | , !), operator precedence, and more String methods. Combined with Scanner, you will build programs that make decisions based on user input. |
Related Resources
- Reges & Stepp, Chapter 3 — Additional reading on Scanner and methods
- CodeStepByStep: Expressions — Practice problems