fork_process
fork_process

Reputation: 29

Read only 3 digits in Java

I'm new to Java. In C I would use: scanf("%3i") to read in only 3 digits even if the user inputs 20 digits at the terminal.

I did not find how to do this with scanner.nextInt();

Upvotes: 1

Views: 863

Answers (2)

Lars
Lars

Reputation: 11

You might want to test, if the input is a number. If this is the case, you can scan a string and cut it to three chars and parse it to an int.

    // Declaration
    Scanner scan = new Scanner(System.in);
    String string = "";

    // Scanner
    System.out.println("Enter a number with 3 digits: ");
    while (!scan.hasNextInt()) scan.next();
    string = scan.next();

    // Cut the string if it is longer than 3 digits
    if (string.length() > 3) string = string.substring(0, 3);
    // Parse string to int
    int threeDigitInt = Integer.parseInt(string);

Upvotes: 1

Jackkobec
Jackkobec

Reputation: 6705

The simplest solution without dancing with trampoline is:

final int input = Integer.parseInt(new Scanner(System.in).nextLine().substring(0, 3));

Upvotes: 0

Related Questions