lundi 2 mars 2020

Java Ternary operator outputs different result than if else statement

I'm writing a program that takes a number and removes the trailing zeros if the number is an integer. I am using the ternary operator but it doesn't work as expected. But if I write it as a if else statement it works.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        double number = scanner.nextDouble();
        System.out.println(((int)number == (double)number) ? (int)number : number); // Always outputs a double

        if ((int)number == (double)number) { // Outputs correct result
            System.out.println((int)number);
        }
        else {
            System.out.println(number);
        }
    }

}

For example if I input 5 i get

5.0
5

if I input 7.3 I get

7.3
7.3

So it seems that it works for the if else statement but not the ternary operator.

Aucun commentaire:

Enregistrer un commentaire