JInput Manipulation - rFronteddu/general_wiki GitHub Wiki
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();
}
}
// (...) 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();
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) { ... }
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();
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();
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
while (sc.hasNext()) {
System.out.println(sc.next());
}
Or
while (sc.hasNextLine()) {
String line = sc.nextLine();
System.out.println(line);
}
You can combine multiple separators using regex inside useDelimiter(): [pattern1|pattern2|...] for flexible input parsing
sc.useDelimiter("[,;\\s]+"); // comma, semicolon, or whitespace
Always check with hasNext() before reading to avoid InputMismatchException.
if (sc.hasNextInt()) {
int val = sc.nextInt();
} else {
sc.next(); // skip invalid token
}
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);
}
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();
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();
}
while (true) {
String input = sc.nextLine();
if (input.equalsIgnoreCase("exit")) break;
process(input);
}
When input is huge (like in algorithmic problems), Scanner can be slow.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
It’s faster than Scanner because it reads larger chunks at once. But you must do most conversion by hand.
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!");
}
}
- 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);
}
}
}
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();
}
}
}
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);
}
}
}