Reading input with Scanner
Scanner reads what the user types. It lives in the java.util package, so import it first:
import java.util.Scanner;
public class Greet {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Your name: ");
String name = sc.nextLine();
System.out.print("Your age: ");
int age = sc.nextInt();
System.out.println("Hello " + name + ", next year you will be " + (age + 1));
sc.close();
}
}
Scanner methods
| Method | Reads | Example input |
|---|---|---|
nextInt() | an int | 25 |
nextDouble() | a double | 72.5 |
nextLong() | a long | 9876543210 |
nextBoolean() | a boolean | true |
next() | one word (stops at a space) | Ranchi |
nextLine() | the whole line, spaces included | Asha Kumari |
Create one Scanner for System.in and reuse it. Close it at the end of the program.
The nextLine trap
int age = sc.nextInt(); // user types 16 and presses Enter
String city = sc.nextLine(); // returns "" immediately!
nextInt() reads 16 but leaves the Enter key (\n) waiting. The next nextLine() reads that empty remainder. The fix is to read and throw away the rest of the line:
int age = sc.nextInt();
sc.nextLine(); // consume the leftover newline
String city = sc.nextLine();
Another fix: read every line with nextLine() and convert: int age = Integer.parseInt(sc.nextLine());.
Formatted output with printf
System.out.printf prints using a format string with placeholders:
String item = "Pen";
int qty = 3;
double price = 12.5;
System.out.printf("%s x %d = Rs %.2f%n", item, qty, qty * price);
Pen x 3 = Rs 37.50
| Placeholder | For | Example |
|---|---|---|
%d | whole numbers | %d with 42 gives 42 |
%f | decimals | %.2f with 3.14159 gives 3.14 |
%s | text | %s with "Java" gives Java |
%c | a character | %c with 'A' gives A |
%n | a new line | works on every operating system |
%5d | width 5, right-aligned | 42 |
%-10s | width 10, left-aligned | Java |
String.format works the same way but returns the text instead of printing it:
String line = String.format("%-8s%6.1f", "Maths", 91.5);
A neat bill with printf
public class Bill {
public static void main(String[] args) {
System.out.printf("%-10s%5s%10s%n", "Item", "Qty", "Amount");
System.out.printf("%-10s%5d%10.2f%n", "Notebook", 4, 4 * 45.0);
System.out.printf("%-10s%5d%10.2f%n", "Pencil", 10, 10 * 5.5);
}
}
Item Qty Amount
Notebook 4 180.00
Pencil 10 55.00
The Math class
Math is in java.lang, so it needs no import. All its methods are static: call them on the class.
| Method | Result | Example |
|---|---|---|
Math.sqrt(x) | square root | Math.sqrt(49) is 7.0 |
Math.pow(a, b) | a to the power b | Math.pow(2, 10) is 1024.0 |
Math.abs(x) | absolute value | Math.abs(-7) is 7 |
Math.max(a, b) | larger value | Math.max(4, 9) is 9 |
Math.min(a, b) | smaller value | Math.min(4, 9) is 4 |
Math.round(x) | nearest whole number | Math.round(2.5) is 3 |
Math.ceil(x) | round up | Math.ceil(4.1) is 5.0 |
Math.floor(x) | round down | Math.floor(4.9) is 4.0 |
Math.random() | random double, 0.0 up to (not including) 1.0 | |
Math.PI | 3.141592653589793 |
Random whole numbers
int dice = (int) (Math.random() * 6) + 1; // 1 to 6
Example: area of a circle from user input
import java.util.Scanner;
public class Circle {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Radius: ");
double r = sc.nextDouble();
double area = Math.PI * Math.pow(r, 2);
System.out.printf("Area = %.2f%n", area);
sc.close();
}
}
Radius: 7
Area = 153.94
Common mistakes
- Forgetting
import java.util.Scanner;, so the compiler says "cannot find symbol". - Calling
nextLine()right afternextInt()and getting an empty string. - Typing text when the program calls
nextInt(): this throwsInputMismatchException. - Using
%dfor adoubleinprintf: this throwsIllegalFormatConversionException. Use%f. - Expecting
Math.sqrtorMath.powto return anint. They returndouble.
Key points
Scanner sc = new Scanner(System.in);reads keyboard input;nextInt,nextDouble,next,nextLineread different kinds of value.- After
nextInt()ornextDouble(), callnextLine()once before reading a full line. printfuses%d,%f,%s,%n;%.2fgives two decimal places.Mathmethods are static:Math.sqrt,Math.pow,Math.max,Math.round,Math.random.
Practice questions
1. What is the difference between next() and nextLine()?
next() reads one word and stops at a space. nextLine() reads everything up to the end of the line, including spaces.
2. What does System.out.printf("%6.2f|", 3.14159); print?
3.14|: two decimal places, padded to a width of 6 characters.
3. Write an expression that gives a random whole number from 10 to 20, inclusive.
int n = (int) (Math.random() * 11) + 10;
Math.random() * 11 gives 0.0 up to 10.99..., so the cast gives 0 to 10, plus 10 gives 10 to 20.
4. Read two numbers and print the larger one using Math.max.
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println("Larger: " + Math.max(a, b));5. What do Math.round(4.5), Math.ceil(4.2) and Math.floor(-4.2) return?
5, 5.0 and -5.0. floor always goes down, so -4.2 becomes -5.0.