Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Java

Idiom #278 Read one line from the standard input

Read one line into the string line.

Explain what happens if EOF is reached.

import java.util.Scanner;
Scanner s = new Scanner(System.in);
String line = s.nextLine();
s.close();

The `nextLine` method will throw `NoSuchElementException` when no line is found, and `IllegalStateException` when the scanner is closed.
import java.util.Scanner;
String line = null;
Scanner in = new Scanner(System.in);
if(in.hasNextLine())
    line = in.nextLine();

On EOF, nextLine() would throw NoSuchElementException
with Ada.Text_IO;
Line : constant String := Ada.Text_IO.Get_Line;

End_Error is raised if EOF is reached.

New implementation...
< >
programming-idioms.org