简体   繁体   中英

Java > int to double(Scanner>System.out)

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

}

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
}

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM