首先,我很新。所以,当一切都是 int 时,我能够让它运行,但是由于某种原因将它更改为 double,我只能输入第一个值并且它出错。我不明白为什么我不能这样做:
int datVal = Integer.parseInt(inNum);
double [] iOne;
iOne = new double[datVal];
在我运行它或调试它之前没有错误。这是我所拥有的:
import java.util.Arrays;
import javax.swing.JOptionPane;
public class arStats2 {
public static void main(String[] args) {
double med, men, min, max;
String inNum = JOptionPane.showInputDialog("Enter the number of data values:");
int datVal = Integer.parseInt(inNum);
double [] iOne;
iOne = new double[datVal];
double [] iTwo;
iTwo = new double[datVal];
int index=0;
for (index=0; index < iOne.length; index++) {
String value = JOptionPane.showInputDialog("Input a data value:");
int valIn = Integer.parseInt(value);
iOne[index] = valIn;
}
System.arraycopy(iOne, 0, iTwo, 0, iOne.length);
Arrays.sort(iOne);
String out1 = "Sorted data: ";
for (int i=0; i<iOne.length; i++) {
out1 = out1 +iOne[i]+"";
}
out1 = out1 +"\n";
String out2 = "Original data: ";
for (int i2=0; i2<iTwo.length; i2++) {
out2 = out2 +iTwo[i2] + "";
}
out2 = out2 +"\n";
med = median(iOne);
men = mean(iTwo);
max = computeMax(iOne);
min = computeMin(iOne);
JOptionPane.showMessageDialog(null, out2 +out1 +"Min Value: " +min +"\n"
+"Max value: " +max +"\n"
+"Median value: " +med +"\n"
+"Mean value: " +men +"\n");
}
public static double median(double[] iOne) {
double med;
int index, indexHi, indexLo;
if ((iOne.length %2) !=0) {
index = iOne.length / 2;
med = iOne[index];
}
else {
indexHi = iOne.length / 2;
indexLo = indexHi = 1;
med = (iOne[indexLo] + iOne[indexHi])/2;
}
return med;
}
public static double mean(double[] iOne) {
double sum = 0;
for (int i = 0; i < iOne.length; i++) {
sum += iOne[i];
}
return sum / iOne.length;
}
public static double computeMax(double[] iOne) {
double max = (iOne.length - 1);
return max;
}
public static double computeMin(double[] iOne) {
double min;
min = iOne[0];
return min;
}
}
错误是:
Exception in thread "main" java.lang.NumberFormatException: For input string: "7.2"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:456)
at java.lang.Integer.parseInt(Integer.java:497)
at arStats2.main(arStats2.java:25)