Error of non-convertible types in java

I have the following code:

import javax.swing.JOptionPane;

public class Excercise613 {
    /** 
      *  Display the prompt to the user; wait for the user to enter
      *  a whole number; return it.  
      */            

    public static int askInt(String prompt) {    
        String s = JOptionPane.showInputDialog(prompt);
        Double d = Double.parseDouble(s);
        return d >= 0 ? (int) d : (int) (d - 1);
    } // End of method
} // End of class

When I compile this, I get an error message at the bottom of the screen that says "non-convertible types". required: int; found: java.lang.Double "And then it highlights the code fragment (int) d".

What am I doing wrong here? Why doesn't casting work?

+4
source share
1 answer

Use the doubleValue () function.

For instance:

import javax.swing.JOptionPane;

public class Excercise613 {
    // Display the prompt to the user; wait for the user to enter a whole number; 
    // return it.  
    public static int askInt(String prompt) {    
        String s = JOptionPane.showInputDialog(prompt);
        Double d = Double.parseDouble(s);                     
        return d >= 0 ? (int) d.doubleValue() : (int) (d.doubleValue() - 1);
    } // End of method
} // End of class

Or you can remove the drives (int)and just call d.intValue(). For instance: return d >= 0 ? d.intValue() : (d.intValue() - 1);

+2
source

All Articles