Reputation: 49
It is my first question) Hope someone can help:
I'm trying write next programm: So i have 1 input and max 2 output First of all i am checking if input is (int!) if TRUE i print out message that "YES IT IS INTEGER" and show "saved number in varaible int",
but if i put double, i want to print out message =(" NO it is not INT) + and show it in double format!
Everything is ok while i put int but when i put double it is not correct.
public class Scan {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int check;
System.out.println("Your number? ");
if(sc.hasNextInt()){
check=sc.nextInt();
System.out.println("OKEI "+check+ " IT IS INTEGER! ");}
else if(sc.hasNextDouble()){
check=sc.nextDouble();
System.out.println("Nooo " + check + " NO it is not INT");
}
}
}
Upvotes: 3
Views: 979
Reputation: 11949
While trying your code in Eclipse, there was en error using check = sc.nextDouble()
(check
being an int
), you can fix it like that:
public static void main(final String[] args) {
System.out.println("Your number? ");
final Scanner sc = new Scanner(System.in);
if (sc.hasNextInt()) {
final int check = sc.nextInt();
System.out.println("OKEI " + check + " IT IS INTEGER! ");
} else if (sc.hasNextDouble()) {
final double check = sc.nextDouble();
System.out.println("Nooo " + check + " NO it is not INT");
} else {
System.out.println("Failed.");
}
}
That way, you won't lose any decimal part using Math.floor
or a cast.
Upvotes: 1
Reputation: 842
Cast int to double value, It may help.
else if (sc.hasNextDouble()) {
check = (int) sc.nextDouble();
System.out.println("Nooo " + check + " NO it is not INT");
}
Upvotes: 0
Reputation: 55
Create a new double variable and assign sc.nextDouble() to that double variable.
Example: double checkDouble; ....
else if(sc.hasNextDouble()){
checkDouble=sc.nextDouble();
System.out.println("Nooo " + check + " NO it is not INT");
}
Upvotes: 2
Reputation: 95948
One solution is having check
as a double
instead, and change the check to:
if (check == Math.floor(check))
In your solution, you're trying to assign a double
to an int
. Since it doesn't fit, it'll loose precision and be truncated.
Final solution should look like:
Scanner sc = new Scanner(System.in);
check = sc.nextDouble();
if (check == Math.floor(check)) {
// an "int"
} else {
// not integer
}
Upvotes: 2