read Int Value from Console - Java Language Basics

Java examples for Language Basics:Console

Description

read Int Value from Console

Demo Code


//package com.java2s;
import java.util.Scanner;

public class Main {
    public static void main(String[] argv) throws Exception {
        System.out.println(readIntValue());
    }//  www  .  j  ava2  s  . co m

    public static int readIntValue() {
        boolean isCorrectValue = false;
        Scanner console = new Scanner(System.in);
        int readValue = 0;

        do {
            if (console.hasNextInt()) {
                readValue = console.nextInt();
                isCorrectValue = true;
            } else {
                System.out.print("Please, enter integer value: ");
                console.next();
            }
        } while (!(isCorrectValue));

        return readValue;
    }
}

Related Tutorials