albanian albanian - 9 months ago 27
Java Question

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

}
}

Answer Source

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.