Skip to content
thesarfo

Concept

User Input

Reading user input from the console with Scanner, and using printf to format output inline.

views 0

To take input from the user, you need a few things:

  1. A Scanner object (imported from java.util.Scanner)
  2. scanner.nextLine() — used to take strings as input from a user
  3. scanner.close() — indicates that you’ve stopped receiving input
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("What is your name? ");
String name = scanner.nextLine();
System.out.printf("Hello %s. How old are you? ", name);
int age = scanner.nextInt();
scanner.nextLine(); // cleans up the input buffer
// alternatively, you can use nextLine() to take all the input and convert it to the type you like
System.out.printf("Price of the last thing you bought? ");
int price = Integer.parseInt(scanner.nextLine());
System.out.printf("I see. you are %d years old", age);
scanner.close();
}
}

You can use System.out.print to make sure everything is on the same line. It works the same as System.out.println, just without a newline character at the end.

Instead of using String.format() inside println/print every time you want formatted output, there’s a function called printf that does that right out of the box, without needing String.format() every time.