Curia
Curia

Reputation: 63

Rounding while checking parameters

I have manage to be-able to check the input and tell if its an int or not, and re ask the user if it is not. However I want to add in a check that will convert doubles into ints by rounding them. I played around with the Math.round method, but could not get anything working properly.

public static int getInteger(String prompt)
{
    int input = 0;
    Scanner user_input = new Scanner( System.in );
    System.out.print("Enter a integer: ");

    while (!user_input.hasNextInt()) { 
        System.out.println("Is not a valid number.");
        user_input.next(); 
    }


    return input;
}

Would be great if someone could show me how, cheers.

Upvotes: 1

Views: 111

Answers (2)

dcernahoschi
dcernahoschi

Reputation: 15240

public static int getInteger()
{
    int input = 0;
    Scanner user_input = new Scanner( System.in );
    System.out.print("Enter a integer: ");

    while (!user_input.hasNextInt() && !user_input.hasNextDouble()) {
        System.out.println("Is not a valid number.");

        user_input.next();
    }

    if(user_input.hasNextInt()) {
        input = user_input.nextInt();
    }
    else {
        input = Math.round((float) user_input.nextDouble()); //I assume here that your number is small as you said
    }

    return input;
}

Upvotes: 1

Dan D.
Dan D.

Reputation: 32391

Math.round(double) returns a long. So, in order to transform that to an int you need to do:

int value = (int) Math.round(double);

However, I would suggest in such case to use long instead of int, as the value may not fit into an int:

long value = Math.round(double);

On the other side, Math.round(float) will return an int.

Upvotes: 0

Related Questions