Reading input with Scanner
Every challenge gives you input as text. Most of the time it starts with a count n, then n values. Scanner reads them for you, ignoring spaces and new lines:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] marks = new int[n];
for (int i = 0; i < n; i++) marks[i] = sc.nextInt();
System.out.println("I read " + n + " marks, the last one is " + marks[n - 1]);
}
}Input (what the user types)
4 70 85 92 64
Output
I read 4 marks, the last one is 64
| To read… | Use |
|---|---|
| a whole number | sc.nextInt() (or sc.nextLong() for big ones) |
| a decimal number | sc.nextDouble() |
| one word | sc.next() |
| a whole line, with spaces | sc.nextLine() |
Common mistake: Never write
while (sc.hasNext())in a challenge. The browser never says “the input is over”, so the loop never ends. Read exactlynitems instead.
int or long?
An int stops at about 2.1 billion. If a number goes past that, it silently wraps around to a wrong, often negative, value. A long goes up to about 9 × 10¹⁸:
public class Main {
public static void main(String[] args) {
int big = 2000000000;
int wrong = big + big; // too big for int!
long right = (long) big + big; // turn one into long first
System.out.println(wrong);
System.out.println(right);
}
}Output
-294967296 4000000000
Printing arrays and lots of output
System.out.println(arr) prints something useless like [I@6d06d69c. Use Arrays.toString(arr) while testing. For the real answer, build the text with a StringBuilder and print it once – it's much faster than many small prints:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] squares = new int[6];
for (int i = 0; i < squares.length; i++) squares[i] = i * i;
System.out.println(Arrays.toString(squares)); // good for checking
StringBuilder sb = new StringBuilder(); // good for answers
for (int i = 0; i < squares.length; i++) {
if (i > 0) sb.append(' ');
sb.append(squares[i]);
}
System.out.println(sb);
}
}Output
[0, 1, 4, 9, 16, 25] 0 1 4 9 16 25
Remember: Read with
Scanner, uselongfor big totals, and print answers exactly in the format the challenge asks for – one extra space or word makes the check fail.