Home > other >  Read only 3 digits in Java
Read only 3 digits in Java

Time:05-05

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();

CodePudding user response:

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);

CodePudding user response:

The simplest solution without dancing with trampoline is:

final int input = Integer.parseInt(new Scanner(System.in).nextLine().substring(0, 3));
  •  Tags:  
  • java
  • Related