简体   繁体   中英

How to load parts of a file using jFrame into an ArrayList in Java?

I am writing a program for an assignment that uses a jFrame UI to read the contents of a notepad file full of "grades" (A, B, C, C+ etc) and then calculate the total number of grades, and the highest and lowest grades. In the jFrame, the user inputs a file name (I do not want to use JFileChooser because that is not part of the assignment) and clicks "load" to load the file. I am struggling with the Load() method. So far, I have:

  public ArrayList<LetterGrade> Load(File file) throws FileNotFoundException {

    ArrayList<LetterGrade> grades = new ArrayList();

    try{
        Scanner input = new Scanner(file);
        String grade = input.nextLine();
        grades.add(LetterGrade.grade);
    } catch (FileNotFoundException ex) {
        System.out.printf("ERROR: %s", ex);
    }

    return grades;

I know that there is a problem in the line that says grades.add(LetterGrade.grade) because I can only add a LetterGrade enum (A, AMinus, BPlus, B etc) to the ArrayList "grades" whereas grade is a String. How can I make it so that when Scanner reads the file, it takes each grade and adds it to the ArrayList called "grades"? Also, I only want to take grades that are part of my LetterGrade enum, so would I use an if/else to filter that? Thanks for the help, and I will respond as quickly as possible to questions.

Java isn't able to automatically convert a String with the value of a LetterGrade directly into a LetterGrade . You can write that function yourself. Try doing something like this:

LetterGrade parseGrade(String grade) {
    if(grade.equals("A") return LetterGrade.A;
    // and so on
}

And then, instead of

grades.add(LetterGrade.grade);

in Load() , you would have this:

grades.add(parseGrade(grade));

If you want to check that what you're adding is a valid grade first, have parseGrade() return null if it's an invalid grade, then check for null while adding the grade to grades .

Change LetterGrade.grade to

LetterGrade.valueOf(grade);

LetterGrade.grade would be used to access a variable named grade in the scope of LetterGrade.

You need to convert the String to Enum.

See Lookup enum by string value for more detials

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