Reputation: 1237
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?
Upvotes: 4
Views: 3124
Reputation: 1620
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);
Upvotes: 2