NoCaffine NoCaffine - 1 year ago 53
Java Question

Java: Checking input for a double, but it accepts an int and turns it into a double

So I'm trying to run this program that will check each input to see that the input matches the correct type, int, double, and boolean. However, the double value is giving me trouble. The hasnextDouble accepts an int and the variable turns it into a double. Any help I can get to solve this would be appreciated, along with the explanation as to why, I don't just want an answer, I want to understand.

import java.util.Scanner;

public class TestValidInput
public static void main(String[] args)
Scanner input = new Scanner(;
int anInt = 0;
double aDouble = 0.0;
boolean aBoolean = false;

System.out.printf("%nEnter an integer: ");

System.out.printf("%nYou must only enter an integer: ");

anInt = input.nextInt();

System.out.printf("%n%d%n", anInt);

System.out.printf("%nEnter a double: ");

System.out.printf("%nYou must only enter a double: ");

aDouble = input.nextDouble();

System.out.printf("%n%f%n", aDouble);

System.out.printf("%nEnter a true or a false: ");

System.out.printf("%nYou must only enter a TRUE or FALSE: ");

aBoolean = input.nextBoolean();

System.out.printf("%n%b%n", aBoolean);



Answer Source

Explanation why

with the explanation as to why

Because int value can be represented as double value, in java integer value can be implicitly converted to double, but not vice versa:

double d = 1.0; // valid
double dd = 1; // valid
int i = 1; // valid
int ii = 1.0; // error

How to solve

Any help I can get to solve this

Add check that it's not in integer format:

while(!(input.hasNextDouble() && !input.hasNextInt()))