Java Scanner Read readInt(String prompt)

Here you can find the source of readInt(String prompt)

Description

Writes a prompt to standard out and tries to read an int value from standard in.

License

Open Source License

Parameter

Parameter Description
prompt the question to prompt the user

Return

the first int value which is entered by the user

Declaration

public static int readInt(String prompt) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.Scanner;

public class Main {
    /**//from  w w w . j a v a  2s  .  c o  m
     * Writes a prompt to standard out and tries to read an int value from
     * standard in. This is repeated until an int value is entered.
     * 
     * @param prompt
     *            the question to prompt the user
     * @return the first int value which is entered by the user
     */
    public static int readInt(String prompt) {
        int value = 0;
        boolean intRead = false;
        do {
            System.out.print(prompt);
            try (Scanner line = new Scanner(System.in); Scanner scannerLine = new Scanner(line.nextLine());) {
                if (scannerLine.hasNextInt()) {
                    intRead = true;
                    value = scannerLine.nextInt();
                }
            }
        } while (!intRead);

        return value;
    }
}

Related

  1. readFileFully(InputStream stream)
  2. readFileToList(File file)
  3. readFileWithoutComments(File input)
  4. readFromReader(Scanner scanner)
  5. readFromScanner(Scanner scanner)
  6. readLine(String format, Object... args)
  7. readMatrix(Scanner in, int n)
  8. readPassword(String format, Object... args)
  9. readPositiveInt(String message, Scanner input)