当我在下面运行我的代码时:
import javax.swing.JOptionPane;
public class HelloWorld{
public static void main(String[] args){
String dataStr=JOptionPane.showInputDialog("enter");
if (dataStr!= null){
int data=Integer.parseInt(dataStr);
JOptionPane.showMessageDialog(null,"Ok"+data);
}
}
}
当我输入null时,终端显示以下错误:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
at HelloWorld.main(HelloWorld.java:9)
我认为在添加条件dataStr!=null
之后我不会有这样的错误。
我的代码有什么问题吗?
答案 0 :(得分:0)
从
更改条件 if (dataStr!= null){
到
if (dataStr!= null && (!dataStr.trim().isEmpty())){
答案 1 :(得分:0)
您的问题是从# provide the values for a test dataset (the y estimated should be 1.41)
pvector <- c(0.0036,0.0156,0.0204,0.0325,0.1096,0.1446,0.1843,0.4518)
zobs <- c(0.0971,0.0914,0.1629,0.1623,0.3840,0.5155,0.3648,0.6639)
# make input of the C value
c <- function(y){
gamma(y)/((gamma(y*(1-pvector)))*(gamma(y*pvector)))
}
# make input of the gamma function
F1 <- function(y){
f1 <- function(x){
c*(1-x)^(y*(1-pvector)-1)*x^(y*pvector-1)
}
return (f1)
}
# integration over x
int <- function(y){
integrate (F1(y),lower =0.001, upper =1)
}
# write the function for minimization
f2 <- function(y) {
sum ((int-zobs)^2)
}
# minimization
optim(0.01,f2, method = "Brent", lower =0, upper = 1000, hessian=TRUE)
可以是三件事之一:
JOptionPane.showInputDialog("enter");
(如果对话框被取消)如果您只是在不输入字符串的情况下按Enter键,则返回的值为空字符串null
,这属于第3类。解决问题的最佳方法是:1)在try / catch块中解析String,从而捕获所有无效输入,或2)强制用户仅输入数字数据,例如使用JSlider或JSpinner。
例如:
""