我试图获得最多25个数字的平均值。现在,我对如何将String
解析成数组感到困惑。这是代码:
final int SIZE = 25;
gradeArray = new double[SIZE];
String s;
int numElem = 0;
double average = 0;
do {
s = (String) JOptionPane.showInputDialog("Enter Grade", "");
if (s == null || s == ("")) {
} else {
try {
grades = Double.parseDouble(s);
if (grades > SIZE)
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Your input must be numeric!",
"Bad Data!", 0);
}
}
} while (s != null || !s.equals(""));
SIZE
常量用于测试目的。
答案 0 :(得分:2)
for(int i=0;i<SIZE;i++)
{
s = (String)JOptionPane.showInputDialog("Enter Grade","");
if(s != null && !(s.trim().equals(""))){
gradeArray[i] = Double.parseDouble(s);
}
else{
gradeArray[i] = 0;
}
}
double sum=0;
for(int j=0;j<gradeArray.length;j++)
{
sum+=gradeArray[j];
}
System.out.println("avaerage of grades ="+SIZE+" is ="+(sum/SIZE));
答案 1 :(得分:0)
根据我的理解,你想要读取多达25个双常量作为单个字符串并将它们解析为双数组。
final int SIZE = 25;
gradeArray = new double[SIZE];
String s;
int numElem = 0;
double average = 0;
do {
s = (String) JOptionPane.showInputDialog("Enter Grade", "");
if (s == null || s == ("")) {
} else {
try {
// this will find double values in your string but ignores non double values
Matcher m = Pattern.compile("(?!=\\d\\.\\d\\.)([\\d.]+)").matcher(s);
int temp = 0;
while (m.find())
{
gradeArray[temp] = Double.parseDouble(m.group(1));
temp ++;
if(temp >= SIZE){
break;
}
}
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Your input must be numeric!",
"Bad Data!", 0);
}
}
} while (s != null || !s.equals(""));