JInput Manipulation - rFronteddu/general_wiki GitHub Wiki

Scanner

Scanner Basics

public class ExampleClass {
    public static void main (String[] args) {
        Scanner sc = new Scanner(System.in);

        // while (sc.hasNext()) { ... } keep going as long as there are inputs
        // sc.useDelimiter(","); define custom delimiter, by default uses any whitespace (spaces, tabs, newlines) as a delimiter.


        String inputLine = sc.nextLine(); // reads a full line
        int inputInt = sc.nextInt(); // reads an int
        String word = sc.next(); // read next token
        sc.close();
    }
}

You can feed a String to scanner

    // (...) Alice is 23 years old and weighs 65.5 kg.

    String data = "Alice 23 65.5";
    Scanner sc = new Scanner(data);
    String name = sc.next();
    int age = sc.nextInt();

You can feed a File to scanner

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
    (...)
    try {
        File file = new File("data.txt");
        Scanner sc = new Scanner(file);
        (...)
    } catch(FileNotFoundException e) { ... }

Reading a CSV-like Multi-line Input

Input:

John,25,Engineer
Sara,30,Designer
Mike,28,Developer

Code

    Scanner sc = new Scanner(input);
    while (sc.hasNextLine()) {
         String line = sc.nextLine();
         Scanner lineScanner = new Scanner(line);
         lineScanner.useDelimiter(","); // you can use regex ("[,;\\s]+"); for example comma, semicolon, or whitespace
         
         String name = lineScanner.next();
         int age = lineScanner.nextInt();
         String job = lineScanner.next();
         // use line
         lineScanner.close();
    }
    sc.close();

Blocks Separated By Keyword

    String input = """
        name=Alice;age=23
        name=Bob;age=31
        END
        name=Carol;age=29
        END
    """;

    Scanner sc = new Scanner(input);
    sc.useDelimiter("[=;\\n]+"); // split by '=', ';', or newlines

    while (sc.hasNext()) {
        String token = sc.next().trim();
        if (token.equals("END")) {
            System.out.println("-- End of block --");
            continue;
        }
        String next = sc.hasNext() ? sc.next().trim() : "";
        System.out.println(token + " -> " + next);
    }
    sc.close();

Mixing nextLine() with nextInt() / nextDouble()

After calling nextInt() or similar, the newline (\n) remains in the buffer. Then nextLine() reads that leftover newline, not the next real line. Always consume the newline after numeric input if you plan to call nextLine() next.

    String input = """
        name=Alice;age=23
        name=Bob;age=31
        END
        name=Carol;age=29
        END
        """;

    int age = sc.nextInt();
    sc.nextLine(); // consume the newline
    String name = sc.nextLine(); // now safe

Reading Until EOF (End of File)

while (sc.hasNext()) {
    System.out.println(sc.next());
}

Or

while (sc.hasNextLine()) {
    String line = sc.nextLine();
    System.out.println(line);
}

Using Custom Delimiters and Regex Patterns

You can combine multiple separators using regex inside useDelimiter(): [pattern1|pattern2|...] for flexible input parsing

sc.useDelimiter("[,;\\s]+"); // comma, semicolon, or whitespace

Safe Parsing with hasNextType()

Always check with hasNext() before reading to avoid InputMismatchException.

if (sc.hasNextInt()) {
    int val = sc.nextInt();
} else {
    sc.next(); // skip invalid token
}

Reading Structured Data

First read a count (loop limit), then read repeating fields.

String i = """
        3
        Alice 24
        Bob 30
        Carol 28
        """
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
    String name = sc.next();
    int age = sc.nextInt();
    System.out.println(name + " is " + age);
}

Reading From a File

Sometimes you’ll be given a file and expected to read it cleanly. File-based Scanner always needs try-catch for FileNotFoundException.

Scanner sc = new Scanner(new File("input.txt"));
while (sc.hasNextLine()) {
    String line = sc.nextLine();
    process(line);
}
sc.close();

Handling Multi-Line and Nested Tokens

Pattern: Use nested scanners — outer for lines, inner for tokens.

while (sc.hasNextLine()) {
    String line = sc.nextLine();
    Scanner lineScanner = new Scanner(line);
    lineScanner.useDelimiter(",");
    String name = lineScanner.next();
    int score = lineScanner.nextInt();
    lineScanner.close();
}

Reading Until a Sentinel / Keyword

while (true) {
    String input = sc.nextLine();
    if (input.equalsIgnoreCase("exit")) break;
    process(input);
}

Handling Large Input (Performance Trick)

When input is huge (like in algorithmic problems), Scanner can be slow.

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

BufferedReader

It’s faster than Scanner because it reads larger chunks at once. But you must do most conversion by hand.

Basic Usage

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class BufferedReaderExample {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        System.out.print("Enter your name: ");
        String name = br.readLine();   // reads one full line (no parsing)

        System.out.print("Enter your age: ");
        int age = Integer.parseInt(br.readLine()); // convert to int manually

        System.out.println("Hello " + name + ", you are " + age + " years old!");
    }
}

Reading Multiple Lines Until EOF

  • readLine() returns null when there’s no more input.
  • !line.isEmpty() lets you stop on a blank line (optional).
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class ReadUntilEOF {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String line;

        while ((line = br.readLine()) != null && !line.isEmpty()) {
            System.out.println("Read: " + line);
        }
    }
}

Reading From A File

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFileExample {
    public static void main(String[] args) {
        // Use try-with-resources (try (...) { ... }) to auto-close the reader.
        try (BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Parsing with Split or Tokenizer

import java.io.FileReader;
import java.io.IOException;

public class ParseCSV {
    public static void main(String[] args) throws IOException {
        try (BufferedReader br = new BufferedReader(new FileReader("people.csv"))) {
            String line;
            while ((line = br.readLine()) != null) {
                String[] parts = line.split(","); // split by comma
                String name = parts[0];
                int age = Integer.parseInt(parts[1]);
                System.out.println(name + " is " + age + " years old.");
            }
        }
    }
}

another example:

import java.io.*;
import java.util.StringTokenizer;

public class TokenizerExample {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String line = br.readLine();  // e.g. "10 20 30"

        StringTokenizer st = new StringTokenizer(line);
        while (st.hasMoreTokens()) {
            int value = Integer.parseInt(st.nextToken());
            System.out.println("Token: " + value);
        }
    }
}
⚠️ **GitHub.com Fallback** ⚠️