Questions or a demo for your school?Student? Sit a test
BrainBit Infotech TeachingStart free

Core Java notes · Topic 3 of 20 · 4 min read

Java input and output: Scanner, printf and Math

Java input and output notes with examples: reading input with Scanner, the nextLine trap, formatted output with printf and String.format, and the Math class.

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

MethodReadsExample input
nextInt()an int25
nextDouble()a double72.5
nextLong()a long9876543210
nextBoolean()a booleantrue
next()one word (stops at a space)Ranchi
nextLine()the whole line, spaces includedAsha 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
PlaceholderForExample
%dwhole numbers%d with 42 gives 42
%fdecimals%.2f with 3.14159 gives 3.14
%stext%s with "Java" gives Java
%ca character%c with 'A' gives A
%na new lineworks on every operating system
%5dwidth 5, right-aligned 42
%-10swidth 10, left-alignedJava

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.

MethodResultExample
Math.sqrt(x)square rootMath.sqrt(49) is 7.0
Math.pow(a, b)a to the power bMath.pow(2, 10) is 1024.0
Math.abs(x)absolute valueMath.abs(-7) is 7
Math.max(a, b)larger valueMath.max(4, 9) is 9
Math.min(a, b)smaller valueMath.min(4, 9) is 4
Math.round(x)nearest whole numberMath.round(2.5) is 3
Math.ceil(x)round upMath.ceil(4.1) is 5.0
Math.floor(x)round downMath.floor(4.9) is 4.0
Math.random()random double, 0.0 up to (not including) 1.0
Math.PI3.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 after nextInt() and getting an empty string.
  • Typing text when the program calls nextInt(): this throws InputMismatchException.
  • Using %d for a double in printf: this throws IllegalFormatConversionException. Use %f.
  • Expecting Math.sqrt or Math.pow to return an int. They return double.

Key points

  • Scanner sc = new Scanner(System.in); reads keyboard input; nextInt, nextDouble, next, nextLine read different kinds of value.
  • After nextInt() or nextDouble(), call nextLine() once before reading a full line.
  • printf uses %d, %f, %s, %n; %.2f gives two decimal places.
  • Math methods 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.