在确定某个子字符串值之后,我该如何收集所有内容

时间:2020-10-03 00:59:03

标签: java

在这里,我想收集子字符串后的所有内容并将其设置为特定字段。

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

备份此代码的目标是首先打开并读取一个文件,该文件包含大约20行,如下所示 学生{name = Jill Gall,年龄= 21,gpa = 2.98} 然后,我需要像上面那样将其拆分,首先两次以去除逗号和等号,然后针对每一行收集名称,年龄和双精度值,将其解析,然后将其设置为新的学生对象并返回它们将要保存到的数组,我目前遇到的问题是我无法弄清楚这里是什么用于收集“名称”,“年龄”,“ gpa”之后的所有内容的正确代码,因为我不知道如何设置不同名称的特定子字符串 即时通讯使用此链接作为参考,但我看不出它到底在做什么

How to implement discretionary use of Scanner

2 个答案:

答案 0 :(得分:0)

我认为错误在于以下几行

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

由于文本是while循环中的局部变量,因此上述代码应在String hold1[] = text.Split(",");处引发编译错误。

实际上应该是

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

您可以使用上方inputs的列表来操作您的逻辑

答案 1 :(得分:0)

从外观上看,至少在ArrayList <>声明中,您有一个名为 Student 的类,该类包含 studentName 的成员变量实例。 em>, studentAge studentGPA 。可能看起来像这样( Getter / Setter 方法当然是可选的,被覆盖的 toString()方法也是可选的):

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

我应该认为目标是从学生文本文件中读取每个文件行,其中每个文件行均包含特定学生的姓名,学生的年龄和学生的GPA分数,并为该学生创建一个Student实例在该特定文件行上。直到文件结束为止。如果“学生”文本文件中有20个学生,则 readFromTextFile()方法运行完成后,将有20个特定的Student实例。您的 StudentReader 类可能看起来像这样:

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