Taylor Redeemer
Taylor Redeemer

Reputation: 31

Parsing a string to an array?

I'm trying to get the average of up to 25 numbers. Right now, I'm confused on how to parse a String into an array. Here is the code as it stands:

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(""));

The SIZE constant is for testing purposes.

Upvotes: 0

Views: 96

Answers (2)

Anuswadh
Anuswadh

Reputation: 552

As I understand you want to read up to 25 double constants as a single string and parse them into a double array.

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(""));

Upvotes: 0

Sudhakar Tillapudi
Sudhakar Tillapudi

Reputation: 26209

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));

Upvotes: 2

Related Questions