0

in here i want to collect everything after a substring and set it as their specfic field.

import java.util.ArrayList;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

/**
 * 
 *
 * class StudentReader for retrieveing data from file
 * 
 */
public class StudentReader {
  
  public static Student[] readFromTextFile(String fileName) { 
      ArrayList<Student> result = new ArrayList<Student>();   
      File f = new File(filename);                            
      Scanner n = new Scanner(f);                             
      while (n.hasNextLine()) {                               
            String text = n.nextLine();                       
      }                                                       
      n.close();                                              
                                                              
      String hold1[] = text.Split(",");                       
      String hold2[] = new String[hold1.length];;             
      for(int i = 0; i < hold1.length(); ++i) {               
          hold2[i] = hold1.Split("=");                        
          if (hold2[i].substring(0,3).equals("name")) {       
                                                              
          }                                                   
      }                                                       
      return result.toArray(new Student[0]);                                  
   }
}

backing up the goal of this code is to first open and read a file where it has about 20 lines that look just like this Student{name=Jill Gall,age=21,gpa=2.98} I then need to split it as done above, twice first to get rid of comma and the equals, I then for each line need to collect the value of the name, age and double, parse them and then set them as a new student object and return that array they are going to be saved onto, what I am currently stuck on is that i cannot figure out what's the right code here for collecting everything after "name" "age" "gpa", as i dont know how to set specific substrings for different name im using this link as a reference but I don't see what actually does it

How to implement discretionary use of Scanner

WJS
  • 22,083
  • 3
  • 14
  • 32
  • 1
    All you're doing is reading in the lines but not doing anything with them. You keep assigning each next line to text. – WJS Oct 03 '20 at 01:07

2 Answers2

0

I think the bug is in following lines,

while (n.hasNextLine()) {                               
   String text = n.nextLine();                       
}    

Above code should throw compilation error at String hold1[] = text.Split(","); as text is local variable within while loop.

Actual it should be,

List<String> inputs = new ArrayList<String>()
Scanner n = new Scanner(f);                             
while (n.hasNextLine()) {                               
   inputs.add(n.nextLine());
} 

You can use above inputs list to manipulate your logic

Riyas
  • 201
  • 6
0

By the look of it, at least by your ArrayList<> declaration, you have a class named Student which contains member variable instances of studentName, studentAge, and studentGPA. It might look something like this (the Getter/Setter methods are of course optional as is the overriden toString() method):

public class Student {

    // Member Variables...
    String studentName;
    int studentAge = 0;
    double studentGPA = 0.0d;

    // Constructor 1:
    public Student() {  }

    // Constructor 2: (used to fill instance member variables 
    // right away when a new instance of Student is created)
    public Student(String name, int age, double gpa) { 
        this.studentName = name;
        this.studentAge = age;
        this.studentGPA = gpa;
    }

    // Getters & Setters...
    public String getStudentName() {
        return studentName;
    }

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

    public int getStudentAge() {
        return studentAge;
    }

    public void setStudentAge(int studentAge) {
        this.studentAge = studentAge;
    }

    public double getStudentGPA() {
        return studentGPA;
    }

    public void setStudentGPA(double studentGPA) {
        this.studentGPA = studentGPA;
    }

    @Override
    public String toString() {
        return new StringBuilder("").append(studentName).append(", ")
                    .append(String.valueOf(studentAge)).append(", ")
                    .append(String.valueOf(studentGPA)).toString();
    }
    
}

I should think the goal would be to to read in each file line from the Students text file where each file line consists of a specific student's name, the student's age, and the student's GPA score and create a Student instance for the Student on that particular file line. This is to be done until the end of file. If there are twenty students within the Students text file then, when the readFromTextFile() method has completed running there will be twenty specific instances of Student. Your StudentReader class might look something like this:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 *
 * class StudentReader for retrieving data from file
 * 
 */
public class StudentReader {

    private static final Scanner userInput = new Scanner(System.in);
    private static Student[] studentsArray;
 
    public static void main(String args[]) {
        String underline = "=====================================================";
        String dataFilePath = "StudentsFile.txt";
        System.out.println("Reading in Student data from file named: " + dataFilePath);
        if (args.length >= 1) {
            dataFilePath = args[0].trim();
            if (!new File(dataFilePath).exists()) {
                System.err.println("Data File Not Found! (" + dataFilePath + ")");
                return;
            }
        }
        studentsArray = readFromTextFile(dataFilePath);
    
        System.out.println("Displaying student data in Console Window:");
        displayStudents();
        System.out.println(underline);
    
        System.out.println("Get all Student's GPA score average:");
        double allGPA = getAllStudentsGPAAverage();
        System.out.println("GPA score average for all Students is: --> " + 
                           String.format("%.2f",allGPA));
        System.out.println(underline);
    
        System.out.println("Get a Student's GPA score:");
        String sName = null;
        while (sName == null) {
            System.out.print("Enter a student's name: --> ");
            sName = userInput.nextLine();
            /* Validate that it is a name. Should validate in 
               almost any language including Hindi. From Stack-
               Overflow post: https://stackoverflow.com/a/57037472/4725875    */
            if (sName.matches("^[\\p{L}\\p{M}]+([\\p{L}\\p{Pd}\\p{Zs}'.]*"
                                + "[\\p{L}\\p{M}])+$|^[\\p{L}\\p{M}]+$")) {
                break;
            }
            else {
                System.err.println("Invalid Name! Try again...");
                System.out.println();
                sName = null;
            }
        }
        boolean haveName = isStudent(sName);
        System.out.println("Do we have an instance of "+ sName + 
                           " from data file? --> " + 
                           (haveName ? "Yes" : "No"));
        // Get Student's GPA 
        if (haveName) {
            double sGPA = getStudentGPA(sName);
            System.out.println(sName + "'s GPA score is: --> " + sGPA);
        }
        System.out.println(underline);
    }

    public static Student[] readFromTextFile(String fileName) {
        List<Student> result = new ArrayList<>();
        File f = new File(fileName);
        try (Scanner input = new Scanner(f)) {
            while (input.hasNextLine()) {
                String fileLine = input.nextLine().trim();
                if (fileLine.isEmpty()) {
                    continue;
                }
                String[] lineParts = fileLine.split("\\s{0,},\\s{0,}");
                String studentName = "";
                int studentAge = 0;
                double studentGPA = 0.0d;

                // Get Student Name (if it exists).
                if (lineParts.length >= 1) {
                    studentName = lineParts[0].split("\\s{0,}\\=\\s{0,}")[1];

                    // Get Student Age (if it exists).
                    if (lineParts.length >= 2) {
                        String tmpStrg = lineParts[1].split("\\s{0,}\\=\\s{0,}")[1];
                        // Validate data.
                        if (tmpStrg.matches("\\d+")) {
                            studentAge = Integer.valueOf(tmpStrg);
                        }

                        // Get Student GPA (if it exists).
                        if (lineParts.length >= 3) {
                            tmpStrg = lineParts[2].split("\\s{0,}\\=\\s{0,}")[1];
                            // Validate data.
                            if (tmpStrg.matches("-?\\d+(\\.\\d+)?")) {
                                studentGPA = Double.valueOf(tmpStrg);
                            }
                        }
                    }
                }
                /* Create a new Student instance and pass the student's data
                   into the Student Constructor then add the Student instance 
                   to the 'result' List.               */
                result.add(new Student(studentName, studentAge, studentGPA));
            }
        }
        catch (FileNotFoundException ex) {
            System.err.println(ex);
        }
        return result.toArray(new Student[result.size()]);
    }

    public static void displayStudents() {
        if (studentsArray == null || studentsArray.length == 0) {
            System.err.println("There are no Students within the supplied Students Array!");
            return;
        }
        for (int i = 0; i < studentsArray.length; i++) {
            System.out.println(studentsArray[i].toString());
        }
    }

    public static boolean isStudent(String studentsName) {
        boolean found = false;
        if (studentsArray == null || studentsArray.length == 0) {
            System.err.println("There are no Students within the supplied Students Array!");
            return found;
        } else if (studentsName == null || studentsName.isEmpty()) {
            System.err.println("Student name can not be Null or Null-String (\"\")!");
            return found;
        }
    
        for (int i = 0; i < studentsArray.length; i++) {
            if (studentsArray[i].getStudentName().equalsIgnoreCase(studentsName)) {
                found = true;
                break;
            }
        }
        return found;
    }

    public static double getStudentGPA(String studentsName) {
        double score = 0.0d;
        if (studentsArray == null || studentsArray.length == 0) {
            System.err.println("There are no Students within the supplied Students Array!");
            return score;
        } else if (studentsName == null || studentsName.isEmpty()) {
            System.err.println("Student name can not be Null or Null-String (\"\")!");
            return score;
        }
    
        boolean found = false;
        for (int i = 0; i < studentsArray.length; i++) {
            if (studentsArray[i].getStudentName().equalsIgnoreCase(studentsName)) {
                found = true;
                score = studentsArray[i].getStudentGPA();
                break;
            }
        }
        if (!found) {
            System.err.println("The Student named '" + studentsName + "' could not be found!");
        }
        return score;
    }

    public static double getAllStudentsGPAAverage() {
        double total = 0.0d;
        if (studentsArray == null || studentsArray.length == 0) {
            System.err.println("There are no Students within the supplied Students Array!");
            return total;
        } 
    
        for (int i = 0; i < studentsArray.length; i++) {
            total += studentsArray[i].getStudentGPA();
        }
        return total / (double) studentsArray.length;
    }
}
DevilsHnd
  • 6,334
  • 2
  • 14
  • 19