简体   繁体   中英

Inconvertible types error 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 at the bottom of the screen that says "inconvertible types. required: int; found: java.lang.Double" And then it highlights the "(int) d" piece of code.

What am I doing wrong here? Why isn't the type casting working?

Use the doubleValue() function.

For example:

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 (int) casts and just call d.intValue() . For example: return d >= 0 ? d.intValue() : (d.intValue() - 1); return d >= 0 ? d.intValue() : (d.intValue() - 1);

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