albanian
albanian

Reputation: 13

Integer-restricted only?

How can I limit the input to only integers (no doubles etc)? simple question for someone experienced to answer. if input is anything other than double then display error message, with ability to enter input again

import java.util.Scanner;


public static void main(String[] args) {

    Scanner reader =  new Scanner(System.in);
    int years;
    int minutes;

    System.out.println("Years to Minutes Converter");
    System.out.print("Insert number of years: ");
    years = reader.nextInt();

    minutes = years * 525600;


    System.out.print("That is ");
    System.out.print(minutes);
    System.out.print(" in minutes.");

    }
 }

Upvotes: 0

Views: 75

Answers (2)

Yussef
Yussef

Reputation: 610

Ok I made this:

package reader;

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

        Scanner reader = new Scanner(System. in );
        int years;
        int minutes;
        String data = null;

        System.out.println("Years to Minutes Converter");
        boolean test = false;

        while (test == false) {
            System.out.print("Insert number of years: ");
            String regex = "\\d+";
            data = reader.next();
            test = data.matches(regex);
            if (test == false) {
                System.out.println("There is a problem try again");
            }
        }
        years = Integer.valueOf(data);

        minutes = years * 525600;

        System.out.print("That is ");
        System.out.print(minutes);
        System.out.print(" in minutes.");

    }

}

It will say:

Years to Minutes Converter

Insert number of years: dsds There is a problem try again Insert number of years: .. There is a problem try again Insert number of years: 2 That is 1051200 in minutes.

Upvotes: 0

Hamza Rashid
Hamza Rashid

Reputation: 1387

Use Scanner.hasNextInt()

Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method. The scanner does not advance past any input.

Example code:

Scanner sc = new Scanner(System.in);
System.out.print("Enter number 1: ");

while (!sc.hasNextInt()) 
    sc.next();

int num1 = sc.nextInt();
int num2;

System.out.print("Enter number 2: ");

do {
    while (!sc.hasNextInt()) 
        sc.next();
    num2 = sc.nextInt();
} while (num2 < num1);

System.out.println(num1 + " " + num2);

You don't have to parseInt or worry about NumberFormatException. Note that since hasNextXXX methods doesn't advance past any input, you may have to call next() if you want to skip past the "garbage", as shown above.

Upvotes: 1

Related Questions