Common input, output and arithmetic fragments for Java. See also the Python and C++ versions.

The fragments are meant to go inside main. The Scanner ones need

import java.util.Scanner;

at the top of the file, and create the scanner once:

Scanner in = new Scanner(System.in);
Contents

Reading input

Values separated by spaces or newlines

Scanner skips over spaces and line breaks between values, so these work whether the values are on one line or several:

int n = in.nextInt();
double x = in.nextDouble();
long big = in.nextLong();
String word = in.next();          // one word (stops at a space)

A whole line

String line = in.nextLine();      // the rest of the current line

Common problem: after nextInt() (or nextDouble(), next()), the newline that ended the number is still waiting, so the next nextLine() returns an empty string. Read and discard it first:

int n = in.nextInt();
in.nextLine();                    // skip the rest of the number's line
String title = in.nextLine();     // now reads the next line

Splitting a line into pieces

String line = in.nextLine();                  // "Alice  17 92.5"
String[] parts = line.trim().split("\\s+");   // split at any whitespace
String name = parts[0];                       // "Alice"
int age = Integer.parseInt(parts[1]);         // 17
double score = Double.parseDouble(parts[2]);  // 92.5

split takes a regular expression: "\\s+" means “one or more spaces or tabs”. For commas, use split(",") and trim() each piece:

String[] fields = line.split(",");            // "red, green ,blue"
for (int i = 0; i < fields.length; i++) {
    fields[i] = fields[i].trim();             // "red", "green", "blue"
}

Integer.parseInt(" 17") fails because of the space; trim() first. Integer.parseInt("3.5") also fails: use Double.parseDouble.

A count followed by that many values

int n = in.nextInt();
int[] nums = new int[n];
for (int i = 0; i < n; i++) {
    nums[i] = in.nextInt();
}

Everything until the end of the input

Use this when the problem does not say how many values or lines there will be:

while (in.hasNextInt()) {         // or hasNextDouble(), hasNext()
    int value = in.nextInt();
    // process value
}
while (in.hasNextLine()) {
    String line = in.nextLine().trim();
    if (!line.isEmpty()) {        // skip blank lines, if the problem allows
        // process line
    }
}

Reading from a file

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Prob1 {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner file = new Scanner(new File("data.txt"));
        while (file.hasNextLine()) {
            String line = file.nextLine();
            // process line
        }
        file.close();
    }
}

The file name is relative to the folder the program runs in, which for IntelliJ is usually the project folder (not the src folder). If the file is “not found”, try the full path, such as new File("C:\\Users\\me\\data.txt") (note the doubled backslashes).

Working with numbers

Converting between double and int

int a = (int) 3.7;                // 3  (the cast drops the fraction)
int b = (int) -3.7;               // -3 (rounds toward zero)
double d = 5;                     // 5.0 (int to double is automatic)
long r = Math.round(3.5);         // 4  (Math.round returns a long)
int r2 = (int) Math.round(2.5);   // 3  (halves round up)
double r3 = Math.round(3.14159 * 100) / 100.0;   // 3.14

Division

When both sides are integers, / is integer division and throws away the fraction:

7 / 2                // 3
7 / 2.0              // 3.5   -- one side is a double
(double) a / b       // a/b with the fraction kept (cast BEFORE dividing)
-7 / 2               // -3    -- rounds toward zero
Math.floorDiv(-7, 2) // -4    -- rounds down
7 % 2                // 1     -- remainder
-7 % 2               // -1    -- remainder takes the sign of the left side

A common mistake: double avg = total / count; with int total, count does integer division first, then converts. Write (double) total / count.

Rounding up and down

Math.floor(3.7)      // 3.0  (returns a double)
Math.ceil(3.2)       // 4.0
Math.floor(-3.7)     // -4.0
(int) Math.ceil(3.2) // 4

“Divide and round up” with integers (for example, boxes needed for 7 items at 2 per box) without going through doubles:

static int ceilDiv(int a, int b) {
    return -Math.floorDiv(-a, b);
}

ceilDiv(7, 2)        // 4
ceilDiv(8, 2)        // 4

Overflow

An int holds values up to about 2.1 billion; going past that silently wraps around to a negative number. Use long (up to about 9.2 × 10^18) for large values, and cast before multiplying:

int a = 100000, b = 100000;
long wrong = a * b;              // 1410065408 -- overflowed as int first
long right = (long) a * b;       // 10000000000

Other handy operations

Math.abs(-5)          // 5
Math.min(3, 8)        // 3
Math.max(3, 8)        // 8
Math.pow(2, 10)       // 1024.0 (a double)
Integer.MAX_VALUE     // 2147483647

Math functions

Math.sqrt(2)                       // 1.4142135623730951
Math.PI                            // 3.141592653589793
Math.sin(Math.toRadians(30))       // 0.49999999999999994 -- trig uses radians
Math.toDegrees(Math.atan2(1, 1))   // 45.0
Math.hypot(3, 4)                   // 5.0, distance from (0,0) to (3,4)
Math.log(Math.E)                   // 1.0 (natural log)
Math.log10(100)                    // 2.0
Math.exp(1)                        // 2.718281828459045

Floating-point results are rarely exact (note the sine above). Compare doubles with a tolerance instead of ==:

if (Math.abs(a - b) < 1e-9) {
    System.out.println("equal");
}

Formatting output

System.out.println(0.1 + 0.2) prints 0.30000000000000004. When a problem asks for a specific number of decimal places, use printf:

double x = 3.14159;
System.out.printf("%.2f%n", x);          // 3.14 (%n is a newline)
System.out.printf("%8.2f%n", x);         // "    3.14" (8 wide, right-aligned)
System.out.printf("%-8.2f|%n", x);       // "3.14    |" (left-aligned)
System.out.printf("%,.2f%n", 1234567.891); // 1,234,567.89
System.out.printf("%5d%n", 42);          // "   42"
System.out.printf("%s scored %.1f%n", name, score);
System.out.printf("Total: $%.2f%n", x);  // Total: $3.14
System.out.printf("%.1f%%%n", 25.6);     // 25.6% (%% prints a percent sign)

String.format takes the same codes and returns a String instead of printing:

String s = String.format("%.2f", x);     // "3.14"

Use %d for int and long, %f for double, %s for anything else. Using %d with a double (or %f with an int) causes an error when the program runs.

Match the expected output exactly: extra spaces, missing blank lines, or a different number of decimal places can cause a solution to fail.

Example: average of the input

Reads numbers until the end of the input and prints their average to two decimal places:

import java.util.Scanner;

public class Average {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        double total = 0;
        int count = 0;
        while (in.hasNextDouble()) {
            total += in.nextDouble();
            count++;
        }
        if (count > 0) {
            System.out.printf("%.2f%n", total / count);
        }
    }
}

Example: sorting and searching

The goal of this example is to illustrate reading data, sorting it, and searching for values. It is written to be easy to follow rather than as fast as possible; for instance, the search simply checks every entry.

The program reads a file of names and ages (in years), sorts the entries by age (and by name when two ages are equal), displays them all in order, and then displays the ages of everyone named Parker. Suppose people.txt holds one name and age per line (see Reading from a file for where to put it):

Parker 17
Alex 16
Jordan 17
Parker 15
Casey 16
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

public class People {
    // One entry from the file: a name and an age in years.
    static class Person implements Comparable<Person> {
        String name;
        int age;

        Person(String name, int age) {
            this.name = name;
            this.age = age;
        }

        // Decides the sorted order. Returns a negative number if this
        // person goes before other, a positive number if after, and 0 if
        // they are the same: by age first, and by name when the ages are
        // equal.
        public int compareTo(Person other) {
            if (age != other.age) {
                return Integer.compare(age, other.age);
            }
            return name.compareTo(other.name);
        }
    }

    public static void main(String[] args) throws FileNotFoundException {
        // Read every name and age from the file.
        ArrayList<Person> people = new ArrayList<>();
        Scanner file = new Scanner(new File("people.txt"));
        while (file.hasNext()) {
            String name = file.next();
            int age = file.nextInt();
            people.add(new Person(name, age));
        }
        file.close();

        // Sort. Collections.sort calls compareTo to decide which of two
        // people goes first.
        Collections.sort(people);

        // Display all entries in order.
        for (Person p : people) {
            System.out.println(p.name + " " + p.age);
        }

        // Search: check every entry and display the age of each one
        // named Parker. Compare strings with equals, not ==.
        System.out.println("Ages of Parker:");
        for (Person p : people) {
            if (p.name.equals("Parker")) {
                System.out.println(p.age);
            }
        }
    }
}

Output:

Parker 15
Alex 16
Casey 16
Jordan 17
Parker 17
Ages of Parker:
15
17

Names are compared character by character, and every uppercase letter comes before every lowercase one, so "Zoe" sorts before "adam".