Java Scanner Read readPositiveInt(String message, Scanner input)

Here you can find the source of readPositiveInt(String message, Scanner input)

Description

Read in a positive integer, which may come from a configuration file

License

Apache License

Parameter

Parameter Description
message output message if read fails
input scanner corresponding to input

Return

positive integer read in

Declaration

public static int readPositiveInt(String message, Scanner input) throws Exception 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.util.Scanner;

public class Main {
    private final static String SEPARATOR = "#";

    /**/*from  w  w  w .j ava 2s .c o  m*/
     * Read in a positive integer, which may come from a configuration file
     * 
     * @param message
     *            output message if read fails
     * @param input
     *            scanner corresponding to input
     *            
     * @return positive integer read in
     * 
     * */
    public static int readPositiveInt(String message, Scanner input) throws Exception {
        int value = Integer.parseInt(getNextInput(input));
        if (value < 1) {
            throwException("Error.  Illegal configuration parameter: " + message + ": " + value);
        }
        return value;
    }

    /**
     * read next input string
     * 
     * @param scan
     *            Scanner corresponding to input
     * 
     * @return next input string
     * 
     * */
    public static String getNextInput(Scanner scan) {
        String word = scan.nextLine();
        String word2 = (word.split(SEPARATOR)[0]);
        return word2.trim();
    }

    /**
     * Print a message and throw an exception
     * 
     * @param message
     *            message to print
     * 
     * */
    public static void throwException(String message) throws Exception {
        System.out.println(message);
        throw new Exception();
    }
}

Related

  1. readFromScanner(Scanner scanner)
  2. readInt(String prompt)
  3. readLine(String format, Object... args)
  4. readMatrix(Scanner in, int n)
  5. readPassword(String format, Object... args)
  6. readSystemInToIntArrayList()
  7. readWholeString(Scanner s)