[英]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
当我编译它时,我在屏幕底部出现一个错误,上面写着“不可转换的类型.required:int; found: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);
return d >= 0 ? d.intValue() : (d.intValue() - 1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.