【问题标题】:how do i collect everything after a certain substring value我如何在某个子字符串值之后收集所有内容
【发布时间】:2021-01-18 14:45:43
【问题描述】:

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

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,age=21,gpa=2.98} 然后我需要像上面那样拆分它,首先两次去掉逗号和等号,然后我需要为每一行收集名称、年龄和双精度的值,解析它们,然后将它们设置为新的学生对象并返回他们将被保存到的那个数组,我目前坚持的是我无法弄清楚这里收集“name”“age”“gpa”之后所有内容的正确代码是什么,因为我不知道如何设置不同名称的特定子字符串 我使用这个链接作为参考,但我不知道它实际上是做什么的

How to implement discretionary use of Scanner

【问题讨论】:

  • 您所做的只是阅读这些行,而不是对它们做任何事情。您不断将下一行分配给文本。

标签: java


【解决方案1】:

我认为错误在于以下几行,

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

上面的代码应该在String hold1[] = text.Split(","); 处抛出编译错误,因为文本是while 循环中的局部变量。

应该是这样的,

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

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

【讨论】:

    【解决方案2】:

    从外观上看,至少通过您的 ArrayList 声明,您有一个名为 Student 的类,其中包含 studentName 的成员变量实例em>、studentAgestudentGPA。它可能看起来像这样(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 分数组成,并为学生创建一个学生实例在那个特定的文件行上。这是在文件结束之前完成的。如果学生文本文件中有 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;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-12
      • 2010-12-23
      • 2018-11-15
      • 1970-01-01
      • 2020-01-06
      相关资源
      最近更新 更多