Kestrel Exams kestrel logo KESTREL EXAMSPRACTICE TO PASS
Java19 min readCode verified

Console input with Scanner: nextInt, nextLine and the empty line

A Scanner turns what the user types into Strings, ints and doubles. This guide builds a campsite booking desk one question at a time, through the empty-line trap, typos, the plus sign and the rule of one Scanner per program. Every listing was compiled and run on OpenJDK 21.

Practice this topic in the free app →All Java guides

A campsite desk and a stream of characters#

Picture the desk at a campground. A camper walks up and the clerk asks: name, nights, people. This guide builds that desk as one Java program, CampDesk, one question at a time, with the real output after every step.

The camper’s answers reach the program as one long stream: characters, one after another, in the order they were typed. Pressing Enter adds one more character, the newline, which Java writes as \n. Typing 3, Enter, 2, Enter sends four characters: 3, \n, 2, \n.

That stream is System.in, the standard input: the keyboard by default, though it can be connected to a file. (System.out, the standard output, is its partner.) System.in has no idea what a number is. A Scanner does: it reads the stream, splits it into pieces and converts each piece to the type you ask for. The Scanner is our clerk.

Picture the clerk keeping one finger on the stream, where reading stopped. Every read starts at the finger and moves it forward. Hold on to that finger: it explains every surprise in this guide.

Python’s input() always reads a whole line. Java’s Scanner can also read one word or number at a time: handy, and the source of this topic’s famous trap.

Importing and creating a Scanner#

You know the shape of a declaration: type, name, equals sign, value, as in int nights = 3;. A Scanner uses the same shape; the one new part is the value on the right, a brand-new object.

First, at the top of the file: import java.util.Scanner;. Scanner lives in the package java.util, a named group of classes, like a folder. String and System never needed an import because they live in java.lang, the one package every file gets automatically. That pays off your first program: System is a class in java.lang, out is its output stream, and println is a method of that stream.

Then, inside main, one line that does two separate jobs:

Scanner in = new Scanner(System.in);
PartJob
Scanner inDeclares a reference variable named in. A reference variable holds an arrow to an object, not the object. No Scanner exists yet.
new Scanner(System.in)Creates a Scanner object that reads System.in.
=Points in at the new object.

Nothing is read yet. Reading happens only when you call a method such as nextLine(). In every output on this page, bold text is what the camper typed, shown at the moment the program read it.

CampDesk.java
import java.util.Scanner;

public class CampDesk {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Name on the booking: ");
        String name = in.nextLine();
        System.out.println("Welcome to Pine Hollow, " + name + "!");
    }
}
Name on the booking: Mei Okafor
Welcome to Pine Hollow, Mei Okafor!

nextLine() waited, read everything up to the Enter key, space included, and returned it as a String. In the print, the spaces inside the quotes print exactly as written, and name is replaced by its value.

Try it first

Delete the import line and compile again. What does the compiler say?

Show the answer

The compiler stops with error: cannot find symbol and symbol: class Scanner, twice: once for the type and once after new. Without the import, it does not know where Scanner lives.

Prompts: print, not println#

A prompt tells the user what to type. print leaves the cursor right after it, so the answer appears beside the question; println drops the camper to the next line. So prompts usually use print and end with a colon and a space: "Nights: ". A println prompt is not wrong if an assignment asks for one. The console output guide covers print, println and printf.

nextInt, nextDouble, next and nextLine#

Three Scanner methods read one token: a run of characters with no whitespace (spaces, tabs or newlines) in it. The fourth reads a line.

MethodReturnsWhat it readsThe Enter key
nextInt()intSkips whitespace, reads one token, converts it.Left in the stream; the finger stops just before it.
nextDouble()doubleThe same. Typing 20 gives 20.0; 24.5 gives 24.5.Left in the stream.
next()StringThe same, kept as text. Stops at the first space.Left in the stream.
nextLine()StringFrom the finger to the end of the line, spaces included. Skips nothing first.Read and thrown away; not in the String.

nextBoolean() works the same way for true or false.

The desk now asks every question and charges $24.50 a night. printf with %.2f prints a double to two decimal places.

One catch: nextInt and nextDouble follow the computer’s language settings. On a computer set up for a country that writes 24,5, typing 24.5 throws InputMismatchException. Double.parseDouble always expects a point.

Try it first

The camper books 3 nights and pays a $20 deposit. What total and balance should print, and what range would make sense?

Show the answer

$73.50 and $53.50. Three nights at $20 to $25 must land between $60 and $75, so a total like $7.35 would be wrong at a glance.

CampDesk.java
import java.util.Scanner;

public class CampDesk {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Name on the booking: ");
        String name = in.nextLine();          // the whole line, spaces included
        System.out.print("Site letter: ");
        String site = in.next();              // one token, as text
        System.out.print("Nights: ");
        int nights = in.nextInt();            // one token, converted to an int
        System.out.print("Deposit paid: $");
        double deposit = in.nextDouble();     // one token, converted to a double

        double total = nights * 24.50;        // $24.50 per night
        System.out.println("Booking for " + name + ", site " + site + ", " + nights + " nights");
        System.out.printf("Total $%.2f, balance due $%.2f%n", total, total - deposit);
    }
}
Name on the booking: Mei Okafor
Site letter: B
Nights: 3
Deposit paid: $20
Booking for Mei Okafor, site B, 3 nights
Total $73.50, balance due $53.50

The prediction matches. One quiet detail: after next() read B, its Enter was still in the stream, yet nextInt() worked. Token reads skip whitespace first, and a newline is whitespace. They ignore lines completely: typing 3 20 on the Nights line would answer the Deposit question too, without waiting. Only nextLine() skips nothing.

A word where a number should be#

Try it first

Strip the desk down to one question. What happens if the camper types the word two for the nights?

Show the answer

An InputMismatchException. nextInt() found a token, but it cannot be converted to an int.

CampDesk.java
import java.util.Scanner;

public class CampDesk {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Nights: ");
        int nights = in.nextInt();
        System.out.println("Booked for " + nights + " nights.");
    }
}
Nights: two
Exception in thread "main" java.util.InputMismatchException
	at java.base/java.util.Scanner.throwFor(Scanner.java:947)
	at java.base/java.util.Scanner.next(Scanner.java:1602)
	at java.base/java.util.Scanner.nextInt(Scanner.java:2267)
	at java.base/java.util.Scanner.nextInt(Scanner.java:2221)
	at CampDesk.main(CampDesk.java:7)

This is a runtime exception: the code compiled, and the problem appeared only when it ran. Read a stack trace from the top for the what, then find the first line naming your own class for the where. The java.util.Scanner lines are inside Scanner; CampDesk.java:7 is yours, the nextInt().

Catching it so the desk can ask again uses try and catch, covered in the exception handling guide. One warning for then: the bad token is not used up. two is still waiting, so the catch block must throw it away with in.nextLine(), or the next nextInt() fails on it again, forever. Scanner’s hasNextInt() also returns true if the next token is a whole number, without reading it.

The empty line after nextInt#

The manager wants the nights and the people first, to check availability, and the name last. Same reads, new order.

Try it first

The camper types 3, Enter, 2, Enter, Mei Okafor, Enter. What will name hold? (The square brackets show where it starts and ends.)

Show the answer

An empty String. The name prompt does not even wait.

CampDesk.java
import java.util.Scanner;

public class CampDesk {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Nights: ");
        int nights = in.nextInt();
        System.out.print("People: ");
        int people = in.nextInt();
        System.out.print("Name on the booking: ");
        String name = in.nextLine();
        System.out.println("Booking for [" + name + "], " + nights + " nights, " + people + " people");
    }
}
Nights: 3
People: 2
Name on the booking: Booking for [], 3 nights, 2 people

The name prompt appeared, and the next thing printed was the booking, with nothing between the square brackets. The camper never got to type, and a tent is now booked under no name at all. This is the most famous Scanner trap.

Shrink it to the smallest case. Look only at the People line: 2 and Enter, two characters.

StepLine (finger is |)What happened
Before| 2 \nThe finger waits at the start.
nextInt()2 | \nReads the token 2, stops before the newline.
nextLine()2 \n |Reads to the end of the line: zero characters. Steps over the \n and returns "".

nextLine() did its job: it returned the rest of the line, which was empty, and Mei Okafor was never read. The trap needs a token read (nextInt, nextDouble or next) and then nextLine(). The other order is safe.

Trap check: is there a nextLine() after a token read?

Every time you write nextLine(), look at the read just before it. If it was a token read, the rest of that line, usually just the \n, is still waiting, and this nextLine() returns it.

Two fixes that work, and two that do not#

Fix 1: throw away the rest of the line. Call nextLine() on its own straight after the last token read, and ignore what it returns. It eats the leftover newline.

CampDesk.java
import java.util.Scanner;

public class CampDesk {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Nights: ");
        int nights = in.nextInt();
        System.out.print("People: ");
        int people = in.nextInt();
        in.nextLine();                        // throw away the rest of the People line
        System.out.print("Name on the booking: ");
        String name = in.nextLine();
        System.out.println("Booking for [" + name + "], " + nights + " nights, " + people + " people");
    }
}
Nights: 3
People: 2
Name on the booking: Mei Okafor
Booking for [Mei Okafor], 3 nights, 2 people

Fix 2: read every answer as a line, then convert it. If every read is nextLine(), no read stops halfway through a line, so nothing is left over. Integer.parseInt turns the text "3" into the int 3; Double.parseDouble does the same for a double.

int nights = Integer.parseInt(in.nextLine());   // read the line, then convert
int people = Integer.parseInt(in.nextLine());
String name = in.nextLine();

Both work. Fix 1 is quick to add to existing code. Fix 2 is the better habit, with no newline to remember, and every listing from here on uses it. With Fix 2, a typed two throws NumberFormatException: For input string: "two" from parseInt instead. So does a stray space, as in "3 "; Integer.parseInt(in.nextLine().trim()) ignores spaces at either end.

Two popular “fixes” do not work:

  • Reading the name with next(). It skips the newline but reads one token, so the name becomes Mei, and Okafor stays behind to break the next read.
  • A second Scanner for the name. Typed by hand it often seems to work; when the answers arrive all at once, as in an autograder, it fails. The one-Scanner section shows it failing for real.

4 nights plus 3 more prints 43#

Try it first

A camper booked 4 nights and wants 3 more. Both are ints. Predict the two lines.

Show the answer

43, then 7.

CampDesk.java
import java.util.Scanner;

public class CampDesk {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Nights booked: ");
        int booked = Integer.parseInt(in.nextLine());
        System.out.print("Extra nights: ");
        int extra = Integer.parseInt(in.nextLine());
        System.out.println("Total nights: " + booked + extra);
        System.out.println("Total nights: " + (booked + extra));
    }
}
Nights booked: 4
Extra nights: 3
Total nights: 43
Total nights: 7

Both numbers were read correctly. The plus sign runs left to right: "Total nights: " + booked makes a longer String, and the next + joins extra onto it as text. That is concatenation, and no addition happens. The parentheses make booked + extra run first, while both sides are numbers. The console output guide walks through this rule.

Trap check: is there a String to the left of this +?

Before you trust a + in a print, look left. If a String has already appeared, this + joins text. Put arithmetic in parentheses.

System.out and System.err#

System.out has a sibling, System.err, the standard error stream, with the same print and println. Results go to standard output; problems go to standard error.

The desk now refuses zero nights. An if runs its first block when the condition in parentheses is true, and the else block when it is false (the if and switch guide covers it):

Try it first

The camper types 0. Which lines go to System.out, and which to System.err?

Show the answer

Nights: and Next camper, please. go to System.out; the error line goes to System.err. On screen they look the same.

CampDesk.java
import java.util.Scanner;

public class CampDesk {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Nights: ");
        int nights = Integer.parseInt(in.nextLine());
        if (nights < 1) {
            System.err.println("Error: a booking needs at least 1 night.");
        } else {
            System.out.println("Booked for " + nights + " nights.");
        }
        System.out.println("Next camper, please.");
    }
}
Nights: 0
Error: a booking needs at least 1 night.
Next camper, please.

Both appear together because both streams go to the same screen; many editors show the error in red. In a terminal the lines appear in the order they were printed. Some editors collect the two streams separately, so the error line can show up a little earlier or later. Do not rely on the order between the two.

The difference shows when output goes elsewhere. java CampDesk > bookings.txt sends only System.out into the file. The error stays on screen and never lands among the bookings.

One Scanner, passed to every method#

The desk asks for counts again and again, so those lines belong in a method: a named block of code you can call. In static int askCount(String prompt), askCount is the name and prompt is a parameter, a value handed in at the call. int is the type of value the method hands back, and static lets main call it without making an object first. Inside, return hands the value back to the line that called it. The methods guide covers all of this in full. Where should the method get its Scanner?

A new Scanner inside the method is tempting, and typed by hand it usually works. So test it the way an autograder does: every answer at once, from a file, like java CampDesk < answers.txt. The System.setIn line copies that by connecting System.in to a file; you will not need it yourself. throws IOException is there because opening a file can fail.

Try it first

The file holds 3 and 2, one per line. Each call to askCount makes its own Scanner. Will it print 3 nights, 2 people?

Show the answer

No. The first Scanner takes both answers, and the second finds nothing.

The file answers.txt holds:

3
2
CampDesk.java
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;

public class CampDesk {
    static int askCount(String prompt) {
        Scanner in = new Scanner(System.in);          // a brand-new Scanner on every call
        System.out.print(prompt);
        return Integer.parseInt(in.nextLine());
    }

    public static void main(String[] args) throws IOException {
        System.setIn(new FileInputStream("answers.txt"));   // test only: the answers come from a file
        int nights = askCount("Nights: ");
        int people = askCount("People: ");
        System.out.println(nights + " nights, " + people + " people");
    }
}
Nights: People: Exception in thread "main" java.util.NoSuchElementException: No line found
	at java.base/java.util.Scanner.nextLine(Scanner.java:1660)
	at CampDesk.askCount(CampDesk.java:9)
	at CampDesk.main(CampDesk.java:15)

No bold text: nobody typed. The first call read 3; the second crashed with NoSuchElementException: No line found, though 2 was in the file.

A Scanner reads ahead: it grabs a whole block of whatever input is waiting and keeps it in its own memory, called a buffer. A person usually types one line at a time, so only one line is waiting. From a file or a pipe, every line is waiting: the first Scanner took them all, and they vanished with it. The same buffer explains the second-Scanner “fix” for the empty line. The leftover newline sits in the first Scanner’s buffer, so a second Scanner never sees it. Typed by hand, that looks like a fix. When the answers arrive together, the first Scanner has already swallowed the name too.

The fix: one Scanner, made in main and passed to every method as a parameter:

The file answers.txt holds:

3
2
CampDesk.java
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;

public class CampDesk {
    static int askCount(Scanner in, String prompt) {
        System.out.print(prompt);
        return Integer.parseInt(in.nextLine());
    }

    public static void main(String[] args) throws IOException {
        System.setIn(new FileInputStream("answers.txt"));   // test only: the answers come from a file
        Scanner in = new Scanner(System.in);                // the only Scanner in the program
        int nights = askCount(in, "Nights: ");
        int people = askCount(in, "People: ");
        System.out.println(nights + " nights, " + people + " people");
    }
}
Nights: People: 3 nights, 2 people

Nothing is lost. And askCount knows nothing about campsites: with another prompt it reads a number of tents or a game score. One method, written once, for any whole-number question: that is what parameters buy you. (To read a file on purpose, use new Scanner(new File("answers.txt")); see the file I/O guide.)

Type this one yourself

Do not paste it. Add askMoney(Scanner in, String prompt), which prompts, reads a line and returns a double. Use it for the deposit and print the balance due at $24.50 a night.

Show the answer

The shape of askCount, with double and Double.parseDouble. For 3 nights and $20 it prints Balance due: $53.50.

static double askMoney(Scanner in, String prompt) {
    System.out.print(prompt);
    return Double.parseDouble(in.nextLine());
}

// in main, after the counts:
double deposit = askMoney(in, "Deposit paid: $");
System.out.printf("Balance due: $%.2f%n", nights * 24.50 - deposit);

Do not close the keyboard Scanner#

Files must be closed when you are done with them (the file I/O guide explains why), so closing the keyboard Scanner is tempting. Do not. Closing a Scanner closes the stream it reads, here System.in, and Java cannot reopen it.

Try it first

This desk closes its Scanner, makes a new one and asks for the nights. What happens?

Show the answer

NoSuchElementException: the new Scanner is reading a closed stream.

CampDesk.java
import java.util.Scanner;

public class CampDesk {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        in.close();                                   // "tidying up" too early
        Scanner again = new Scanner(System.in);       // try to start over
        System.out.println("Anything to read? " + again.hasNextLine());
        System.out.println("Why not? " + again.ioException());
        System.out.print("Nights: ");
        int nights = again.nextInt();
        System.out.println("Booked for " + nights + " nights.");
    }
}
Anything to read? false
Why not? java.io.IOException: Stream closed
Nights: Exception in thread "main" java.util.NoSuchElementException
	at java.base/java.util.Scanner.throwFor(Scanner.java:945)
	at java.base/java.util.Scanner.next(Scanner.java:1602)
	at java.base/java.util.Scanner.nextInt(Scanner.java:2267)
	at java.base/java.util.Scanner.nextInt(Scanner.java:2221)
	at CampDesk.main(CampDesk.java:11)

Two methods show the cause. hasNextLine() asks whether a line can be read, without reading it: false. ioException() returns the input error the Scanner hid: Stream closed. Without the close() line it prints null.

The camper’s 3 was waiting in this run, yet it never appears in bold: the read failed without taking it. A real terminal does the same. The rule: never close a Scanner on System.in while input is still needed. If your editor warns of a “resource leak”, ignore it here, or close it as the last line of main.

What was new in this guide#

  1. System.in: one stream of characters, the keyboard by default, with Enter as \n.
  2. import java.util.Scanner;, and no import for java.lang classes like String.
  3. Scanner in = new Scanner(System.in); declares and creates; nothing is read yet.
  4. Prompts with print.
  5. Token reads (nextInt, nextDouble, next) leave the newline; nextLine reads to it.
  6. InputMismatchException for a token of the wrong type.
  7. The empty line, fixed by a throwaway nextLine() or by Integer.parseInt(in.nextLine()).
  8. 4 and 3 print as 43 unless the sum is in parentheses.
  9. System.out for results, System.err for problems.
  10. One Scanner, passed as a parameter, because a Scanner reads ahead.
  11. Closing it closes System.in for good.
One sentence to carry into the exam

A Scanner keeps a finger in one stream of typed characters: nextInt, nextDouble and next stop before the Enter key, and nextLine reads to it. So a nextLine() after a token read returns the empty rest of the line. Make one Scanner, pass it around, and do not close it while input is still needed.

Where these go wrong#

  • No import java.util.Scanner;. The compiler says cannot find symbol. Only java.lang classes come without an import.
  • nextLine() straight after nextInt(). It returns the empty rest of the line. Add a throwaway nextLine(), or read lines and use Integer.parseInt.
  • Storing nextLine() in an int. It returns a String: incompatible types. Convert with Integer.parseInt.
  • "Nights: " + booked + extra. After a String, + joins text, so 4 and 3 print as 43. Write (booked + extra).
  • A new Scanner inside a method. It reads ahead and swallows input, which autograders expose. Pass one Scanner as a parameter.
  • Closing the System.in Scanner early. System.in closes for good: a new Scanner’s next read throws NoSuchElementException, and the closed Scanner itself throws IllegalStateException: Scanner closed.

On the exam: Input questions give the typed lines and ask what prints. Write the characters out, marking each Enter, and move a finger through them read by read. If asked to “write a method” that reads input, take the Scanner as a parameter.

Practice#

Answer each one on paper before you look at the solutions. Every answer that involves running code was checked by compiling and running it.

  1. The user types 4 5 on one line and presses Enter. What are the two lines of output?
    int tents = in.nextInt();
    int tarps = in.nextInt();
    System.out.println(tents + tarps + " items to pack");
    System.out.println("Items: " + tents + tarps);
  2. Find the error, and give a fix that keeps nextLine().
    System.out.print("Lantern count: ");
    int lanterns = in.nextLine();
  3. The user types Pine Hollow Loop and presses Enter. What prints? Watch the spaces.
    String first = in.next();
    String rest = in.nextLine();
    System.out.println("[" + first + "]");
    System.out.println("[" + rest + "]");
  4. A program prints bookings with System.out and warnings with System.err. It is run as java CampDesk > bookings.txt. Where does each kind of message end up?
  5. Write a method askTotal that takes a Scanner as a parameter, asks for the number of adults and then children (one answer per line), and returns the total. It must not create a Scanner.
  6. A program works whenever its author types the answers, but an autograder that feeds them from a file reports NoSuchElementException on the second question. Each reading method starts with Scanner in = new Scanner(System.in);. Explain in one or two sentences.

Solutions#

  1. Each nextInt() reads one token, so both come from one line. Numbers first, so + adds; then a String first, so + joins text:Pack.java
    import java.util.Scanner;
    
    public class Pack {
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            System.out.print("Tents and tarps: ");
            int tents = in.nextInt();
            int tarps = in.nextInt();
            System.out.println(tents + tarps + " items to pack");
            System.out.println("Items: " + tents + tarps);
        }
    }
    Tents and tarps: 4 5
    9 items to pack
    Items: 45
  2. nextLine() returns a String, which cannot be stored in an int:Lanterns.java
    import java.util.Scanner;
    
    public class Lanterns {
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            System.out.print("Lantern count: ");
            int lanterns = in.nextLine();
            System.out.println(lanterns + " lanterns");
        }
    }
    Lanterns.java:7: error: incompatible types: String cannot be converted to int
            int lanterns = in.nextLine();
                                      ^
    1 error

    Fix: int lanterns = Integer.parseInt(in.nextLine());

  3. next() reads Pine and stops at the space; nextLine() reads the rest, starting with that space:Trail.java
    import java.util.Scanner;
    
    public class Trail {
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            System.out.print("Trail name: ");
            String first = in.next();
            String rest = in.nextLine();
            System.out.println("[" + first + "]");
            System.out.println("[" + rest + "]");
        }
    }
    Trail name: Pine Hollow Loop
    [Pine]
    [ Hollow Loop]
  4. Everything printed with System.out goes into bookings.txt, prompts included, because > redirects only standard output. The warnings go to standard error, which is still the screen, so a person sees them and they never land in the file.
  5. Read each answer as a line and convert it:HeadCount.java
    import java.util.Scanner;
    
    public class HeadCount {
        static int askTotal(Scanner in) {
            System.out.print("Adults: ");
            int adults = Integer.parseInt(in.nextLine());
            System.out.print("Children: ");
            int children = Integer.parseInt(in.nextLine());
            return adults + children;
        }
    
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            int people = askTotal(in);
            System.out.println("People: " + people);
        }
    }
    Adults: 2
    Children: 3
    People: 5
  6. The first Scanner read ahead and took every line in the file, so the second found nothing. Typing hid the bug, because only one line waits at a time. Make one Scanner in main and pass it in.

Test-readiness checklist#

These are the items from the course’s Exam 1 topic list that this guide covers. Tick each one only when you can do it without looking.

  • ☐  I can create a Scanner over System.in and explain that line.
  • ☐  I can say how each read method treats spaces and the Enter key.
  • ☐  I can predict the empty line after nextInt then nextLine, and fix it two ways.
  • ☐  I can explain InputMismatchException, and "Nights: " + booked + extra versus "Nights: " + (booked + extra).
  • ☐  I can say where System.out and System.err output goes.
  • ☐  I can pass one Scanner to a method, and say why closing it breaks input.

Test yourself in the free Kestrel Exams app

18 practice questions on console input, with every code answer checked by compiling and running it. Free, offline, no account.

Practice console input →

Frequently asked questions#

How do I read keyboard input in Java?

Add import java.util.Scanner; at the top, create one Scanner with Scanner in = new Scanner(System.in); and call nextLine() for text or nextInt() for a whole number.

Why does nextLine() skip my input after nextInt()?

nextInt() stops just before the newline the Enter key added, so the next nextLine() returns the empty rest of that line without waiting. Call nextLine() once to discard it, or read every answer with nextLine() and convert with Integer.parseInt.

What is the difference between next() and nextLine() in Java?

next() reads one token and stops at the first space or newline. nextLine() reads everything to the end of the line, spaces included, and discards the newline.

What causes InputMismatchException in Java?

nextInt() or nextDouble() found a token that cannot be converted, such as the word two where a number was expected. The program stops at that read unless the exception is caught. It can also happen with 24.5 on a computer set to a language that writes decimals with a comma.

Should I close a Scanner that reads System.in?

Not while input is still needed. Closing it also closes System.in, which cannot be reopened, so later reads throw NoSuchElementException, even from a new Scanner.

Why do I need to import Scanner but not String?

Scanner is in the java.util package, which must be imported. String, System and Math are in java.lang, the only package imported into every file automatically.

Suggest a change

Something here not clear? A topic you wish we covered? Tell us. We read every message, and a request is the fastest way to get a guide written: several of these exist because somebody asked.