简体   繁体   中英

How to parse an array into an object in Java

I've got an assignment to create an app that shows a student's name and final letter grade when their name is selected via a spinner. I've got the spinner set up with the names, and I've read in the names and grades from a text file stored in assets. I used StringBuilder to split all the info from that file into a String array. I'd like to parse that data into a an object called Student so that I can get process the grades for individual students, but I can't figure out how to do that. Any help is appreciated!

The text file:

Name            Test1   Test2   Test3   Final
Adam    Anderson    81  90  85  87
Ben Brown       77  80  68  94
Chris   Cross       74  80  56  62
Don Dare        86  94  90  89
Eric    Earl        96  93  90  98
Fred    Foley       79  92  59  86
Gina    Gray        80  83  95  87
Holly   Hank        74  77  75  78
Ian Ingram      66  64  56  60
Jill    Johnson     90  98  78  89

My code so far:

package lauren.ruff.lab4;

import android.content.res.AssetManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Spinner;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.StringBuilder;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

TextView name, grade;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    String strName;
    String strLastName;
    String strFirstName;
    String strFinalGrade;
    final String[] strSelected = new String[1];

    final int intTest1;
    int intTest2;
    int intTest3;
    int intFinal;
    int intFinalGrade;
    final int[] intSelection = new int[1];

    int intPointsPossible = 400;

    int finalGrades[] = new int[0];

    AssetManager am = getAssets();
    ArrayList<String> list = new ArrayList<String>();
    BufferedReader reader;
    StringBuilder sb = new StringBuilder();
    String[] tempList = new String[0];
    final ArrayList<Integer> finalList = new ArrayList<>();
    String line = " ";
    String item = " ";

    try {
        InputStream input = am.open("grades.txt");
        reader = new BufferedReader(new InputStreamReader(input));

        while (line != null){
            line = reader.readLine();
            list.add(line);

        }

        input.close();

        list.remove(0);

        for (int i = 0; i < list.size(); i++){
            sb.append(i);
        }

        tempList = sb.toString().split("\\s+");

        for (int j = 0; j < tempList.length; j++){
            finalList.add(j);
        }


    } catch (IOException e) {
        e.printStackTrace();
    }

    final Spinner spinner = (Spinner)findViewById(R.id.spName);

    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            intSelection[0] = spinner.getSelectedItemPosition();
            strSelected[0] = spinner.getSelectedItem().toString();

            name = (TextView)findViewById(R.id.tvDisplayName);
            name.setText(strSelected[0]);

            grade = (TextView)findViewById(R.id.tvDisplayGrade);

            if (intSelection[0] == 0){
                int t1 = finalList.get(2);
                int t2 = finalList.get(3);
                int t3 = finalList.get(4);
                int t4 = finalList.get(5);
                Grades(t1,t2,t3,t4);
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    });

}


public String Grades(int t1, int t2, int t3, int t4){
    int test1 = 0, test2 = 0, test3 = 0, finalScore = 0;
    double finalGrade;
    String letterGrade;
    finalGrade = (test1 + test2 + test3 + finalScore)/4;
    if (finalGrade > 93){
        letterGrade = "A";
    }
    else if (finalGrade > 88){
        letterGrade = "B+";
    }
    else if (finalGrade > 83){
        letterGrade = "B";
    }
    else if (finalGrade > 78){
        letterGrade = "C+";
    }
    else if (finalGrade > 73){
        letterGrade = "C";
    }
    else if (finalGrade > 65){
        letterGrade = "D";
    }
    else {
        letterGrade = "F";
    }

    return letterGrade;
}


}

Try Reading txt file and create an Object instead of add to list. Try something like this.

YourObject obj = new YourObject();
try
{
    List<String> yourLines = Files.readAllLines(java.nio.file.Paths.get("./grades.txt"), StandardCharsets.UTF_8);
    for (String line : yourLines) {
        String[] tokens = line.split(" ");
        obj.setName(tokens[0]);
    }
    System.out.println(obj.toString());
}
catch(IOException e)
{
    e.printStackTrace();
}`

new Strudent(String firstName, String lastName, int[] tests, int final)所有数据后,请使用良好的参数调用new Strudent(String firstName, String lastName, int[] tests, int final)

You can create a POJO(Plain java object) class.

public class StudentPOJO{

   private String studentName;
   private String grade;


   public void setStudent(String studentName){
       this.studentName=studentName;
   }

   public void setStudentGrade(String grade){
       this.grade=grade;
   }

   public String getStudentGrade(){
       return grade;
   }

   public String getStudentName(){
       return studentName;
   }

}

This way you can create an object for each student to store his/her information.

I agree with Zorglube on this one. Make a Student class . You already have all the data from the txt file.

However, I really don't understand your use of arrays.

A new String[1] is basically just a String so what's with the array?

Also: on your public String Grades(int t1, int t2, int t3, int t4)

What's the point of having parameters if you're not using them on the method itself at all?

And still on this subject, it seems that what you're expecting here is actually public String Grades(integer[] ints) or public String Grades(List ints)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM