java 中的不可转换类型错误
Inconvertible types error in java
我有以下代码:
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
当我编译它时,我在屏幕底部收到一条错误消息,提示“不可转换的类型。
必填:整数;找到:java.lang.Double" 然后突出显示“(int) d”代码段。
我在这里做错了什么?为什么类型转换不起作用?
使用 doubleValue() 函数。
例如:
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
或者您可以删除 (int)
强制转换并只调用 d.intValue()
。例如:
return d >= 0 ? d.intValue() : (d.intValue() - 1);
我有以下代码:
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
当我编译它时,我在屏幕底部收到一条错误消息,提示“不可转换的类型。 必填:整数;找到:java.lang.Double" 然后突出显示“(int) d”代码段。
我在这里做错了什么?为什么类型转换不起作用?
使用 doubleValue() 函数。
例如:
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
或者您可以删除 (int)
强制转换并只调用 d.intValue()
。例如:
return d >= 0 ? d.intValue() : (d.intValue() - 1);