【问题标题】:JAVA- Read .txt file with mix of strings & integers, store strings in an array and integers in a 2D arrayJAVA- 读取包含字符串和整数的 .txt 文件,将字符串存储在数组中,将整数存储在二维数组中
【发布时间】:2016-12-08 18:56:42
【问题描述】:

我有一个文本文件,其中一行是学生姓名,下一行是 15 个成绩(每个成绩由 2 个空格分隔,并且在行首有一个空格)。

示例:

    John, Elton
      89  97  91  94  82  96  98  67  69  97  87  90  100  80  92
    Johnson, Kay
      96  68  71  70  90  79  69  63  88  75  61  77  100  80  88

    (More data...)


我需要读取包含学生姓名的行并将值存储在字符串数组中,然后读取以下成绩行,将值存储在二维整数数组中。在每行整数中,前 10 个值将被视为作业成绩,而后 5 个值是考试成绩(稍后在计算学生平均成绩时使用)。当我的程序尝试读取第一个学生姓名之后的整数行时,由于“输入不匹配异常”而崩溃。到目前为止,这是我的代码:

import java.io.*;
import java.util.*;

public class Grades
{   
    // Declare constants for array lengths
    private static final int ROWS = 25;
    private static final int COLS = 15;

public static void main(String[] args) throws IOException
{
    // Create new two dimensional integer array to hold students assignment & exam grades
    int[][] grades = new int[ROWS][COLS];

    // Create new string array to hold student names
    String[] students = new String[ROWS];

    // Total number of students
    int numStudents;

    // Display your name
    System.out.println( "YOUR NAME" );

    // Fill the arrays
    numStudents = fillArray( grades, students );

    // Display the data that was just read in
    display(grades, students, numStudents);

}

 // The fillArray method opens & reads student name & grade data from a text file
private static int fillArray(int[][] sGrades, String[] sNames) throws IOException
{
    // Students counter
    int students = 0;   

    // Create the file
    File studentGrades = new File("Grades.txt");

    // Check that the file exists
    if (!studentGrades.exists())
    {
        // Display error message and exit the program
        System.out.println(studentGrades + " not found. Aborting.");
        System.exit(0);
    }

    // Create scanner object to read from the file
    Scanner gradeFile = new Scanner(studentGrades);

    // Read data until the end of the file is reached or the array is full
    while (gradeFile.hasNext() && students < sNames.length)
    {
        // Begin filling the array of student names starting with the first element
        for ( int i = 0; i < ROWS; i++ )
        {
            // Store the students name into the array's current index
            sNames[i] = gradeFile.nextLine();

            // Increment the number of students
            students++;

            // Begin filling in the array of grades starting with the first element

/*************   ERROR OCCURS HERE   ********************/
            for ( int j = 0; j < COLS; j++ )

                // Store the grade into the array's current index
                sGrades[i][j] = gradeFile.nextInt();
/**************                       *******************/
        }
    }
    // Close the file
    gradeFile.close();
    // Return the total number of students
    return students;
}
    // The display method prints Each student's name, 10 assignment 
    // grades and 5 exam grades
    // to the screen, separating each student by a blank line.
total number of students
private static void display(int[][] gradeArray, String [] studentArray, int totalStudents)
{
    //
    for ( int i = 0; i < totalStudents; i++)
    {
        System.out.println();
        //
        System.out.print("STUDENT:     " + studentArray[i]);

        System.out.print("\nASSIGNMENTS: ");
        //
        for ( int j = 0; j < 10; j++)
            //
            System.out.print(gradeArray[i][j] + " ");

        //
        System.out.print("\nEXAMS:       ");

        //
        for ( int k = 10; k < COLS; k++)
            //
            System.out.print(gradeArray[i][k] + " ");
        System.out.println();
    }

'display' 方法的输出应如下所示:

    YOUR NAME

    STUDENT:     John, Elton
    ASSIGNMENTS: 89 97 91 94 82 96 98 67 69 97
    EXAMS:       87 90 100 80 92

    STUDENT:     Johnson, Kay
    ASSIGNMENTS: 96 68 71 70 90 79 69 63 88 75
    EXAMS:       61 77 100 80 88   

    (More output...)

由于程序在我看到任何输出之前就崩溃了,因此我删除了以下试图读取下一个 Integer 以查看发生了什么的代码行。

    for ( int j = 0; j < COLS; j++ )
        sGrades[i][j] = gradeFile.nextInt();

正如我所料,文件的每一行都作为字符串读取,值存储在学生姓名数组中,输出如下:

    STUDENT:     John, Elton
    ASSIGNMENTS: 0 0 0 0 0 0 0 0 0 0
    EXAMS:       0 0 0 0 0

    STUDENT:     89 97 91 94 82 96 98 67 69 97 87 90 100 80 92
    ASSIGNMENTS: 0 0 0 0 0 0 0 0 0 0
    EXAMS:       0 0 0 0 0

    STUDENT:     Johnson, Kay
    ASSIGNMENTS: 0 0 0 0 0 0 0 0 0 0
    EXAMS:       0 0 0 0 0

    STUDENT:     96 68 71 70 90 79 69 63 88 75 61 77 100 80 88
    ASSIGNMENTS: 0 0 0 0 0 0 0 0 0 0
    EXAMS:       0 0 0 0 0

    (More output...)

试图弄清楚我哪里出错了,我的大脑很痛。如果我猜测,我认为这与分隔每个整数的空格有关,导致每行成绩被解释为字符串而不是整数。或者还有什么我可能忽略的?

编辑:我仅限于对这个程序使用更基本的 Java 技术。除了方法头中的throws 子句之外,我不能使用数组列表和异常处理。文件处理仅限于使用 FileScanner 类。没有BufferReaderStringReaderFileReader

【问题讨论】:

    标签: java arrays string file int


    【解决方案1】:

    用如下的 try 和 catch 语句包围你的填充:

             try{
                sNames[i] = gradeFile.nextLine();
                }catch(Exception NoSuchElementException){   
                }
    

    并编写产生类似错误的for循环:

                    for ( int j = 0; j < COLS; j++ ){
                    try{
                        sGrades[i][j]=gradeFile.nextInt() ;
                    }catch(Exception NoSuchElementException){
    
                    }
    
    
                }
                try{
                    gradeFile.nextLine();
                }catch(Exception NoSuchElementException){
    
                }
    

    最后一个gradeFile.nextLine() 在你的for循环(添加整数)之后丢失了,我用try and catch语句添加了它 告诉我它是否有效:)

    【讨论】:

    • 不幸的是,我仅限于使用不允许 try & catch 语句的某些 Java 技术。无论如何,我确实尝试了您的代码,但是当程序尝试将下一个学生姓名读入字符串数组时收到此错误:线程“main”中的异常 java.util.NoSuchElementException:找不到行
    • 哦,好吧,这很奇怪,因为我刚刚尝试过,但没有收到任何错误:
    【解决方案2】:

    我已经编写了一个应用程序来完全做你想做的事。

    这里是:

    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;
    import java.io.StringReader;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    
    public class Main {
    
        //Aka rows
        private static final int NO_STUDENTS = 25;
        //Grades per student. Aka columns.
        private static final int NO_GRADES = 15;
    
        //Names of all the students
        private final String[] STUDENTS = new String[NO_STUDENTS];
    
        //The students grades
        private final int[][] GRADES = new int[NO_STUDENTS][NO_GRADES];
    
        /**
         * Runs the application
         */
        public Main() {
            try {
                //Writes to the arrays from the text file
                parseReults("Results.txt");
                //Prints the results in the format
                printResults();
            } catch (IOException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
    
        }
    
        /**
         * Parses the students names and grades from a text file and writes them to
         * the arrays.
         *
         * @param resultsFile
         */
        private void parseReults(String resultsFile) throws IOException {
            BufferedReader reader = new BufferedReader(
                    new StringReader(getTextFileContents(resultsFile)));
    
            int lineNo = 0;
            int studentNo = 0;
            int gradeNo = 0;
            String line;
    
            //Reads over every line in the file
            while ((line = reader.readLine()) != null) {
                //Is the line number odd, if so read students name else read
                //the grades
                if (lineNo % 2 == 0) {
                    STUDENTS[studentNo] = line;
                    studentNo++;
                } else {
                    GRADES[gradeNo] = getGrades(line);
                    gradeNo++;
                }
    
                lineNo++;
            }
        }
    
        /**
         * Prints the results from the arrays.
         */
        private void printResults() {
            System.out.println("YOUR NAME\n");
    
            for (int i = 0; i < STUDENTS.length; i++) {
                System.out.println("STUDENT: " + STUDENTS[i]);
    
                String assignments = "";
    
                for (int j = 0; j < 9; j++) {
                    assignments += GRADES[i][j] + " ";
                }
    
                System.out.println("ASSIGNMENTS: " + assignments);
    
                String exams = "";
    
                for (int k = 9; k < 15; k++) {
                    exams += GRADES[i][k] + " ";
                }
    
                System.out.println("EXAMS: " + exams);
                System.out.println("");
            }
        }
    
        public static void main(String[] args) throws IOException {
            Main m = new Main();
        }
    
        /**
         * Parses all the students grades from one line of text into an integer
         * array containing all the grades.
         * 
         * @param gradesLine
         * @return 
         */
        private static int[] getGrades(String gradesLine) {
            try {
                int[] grades = new int[NO_GRADES];
    
                StringReader reader = new StringReader(gradesLine);
                reader.read();//Get rid of the first space
    
                for (int i = 0; i < NO_GRADES; i++) {
                    String grade = "";
                    char letter;
    
                    while ((letter = (char) reader.read()) != ' ') {
                        if (letter == '\n' || letter == (char) 65535) {
                            break;
                        }
                        grade += letter;
                    }
    
                    reader.read();//Get red of the second space
                    grades[i] = Integer.parseInt(grade);
                }
    
                return grades;
            } catch (IOException ex) {
                //Isn't happening
            }
    
            return null;//Won't happen
        }
    
        /**
         * Reads an entire text file.
         *
         * @param fileName the name of the file
         * @return the file contents
         */
        private static String getTextFileContents(String fileName)
                throws FileNotFoundException, IOException {
            String contents = "";
    
            try (BufferedReader reader = new BufferedReader(
                    new FileReader(new File(fileName)))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    contents += line + "\n";
                }
            }
    
            return contents;
        }
    }
    

    这是“Results.txt”文件:

    John, Elton
     89  97  91 94  82  96  98  67  69  97  87  90  100  80  92
    Johnson, Kay
     96  68  71  70  90  79  69  63  88  75  61  77  100  80  88
    Amanda, Grey
     35  15  44  88  95  84  85  45  15  95  11  46  98  100  88
    

    最后,这是输出:

    YOUR NAME
    
    STUDENT: John, Elton
    ASSIGNMENTS: 89 97 91 4 82 96 98 67 69 
    EXAMS: 97 87 90 100 80 92 
    
    STUDENT: Johnson, Kay
    ASSIGNMENTS: 96 68 71 70 90 79 69 63 88 
    EXAMS: 75 61 77 100 80 88 
    
    STUDENT: Amanda, Grey
    ASSIGNMENTS: 35 15 44 88 95 84 85 45 15 
    EXAMS: 95 11 46 98 100 88 
    
    STUDENT: null
    ASSIGNMENTS: 0 0 0 0 0 0 0 0 0 
    EXAMS: 0 0 0 0 0 0 
    
    STUDENT: null
    ASSIGNMENTS: 0 0 0 0 0 0 0 0 0 
    EXAMS: 0 0 0 0 0 0 
    
    STUDENT: null
    ASSIGNMENTS: 0 0 0 0 0 0 0 0 0 
    EXAMS: 0 0 0 0 0 0 
    
    STUDENT: null
    ASSIGNMENTS: 0 0 0 0 0 0 0 0 0 
    EXAMS: 0 0 0 0 0 0 
    
    STUDENT: null
    ASSIGNMENTS: 0 0 0 0 0 0 0 0 0 
    EXAMS: 0 0 0 0 0 0 
    
    STUDENT: null
    ASSIGNMENTS: 0 0 0 0 0 0 0 0 0 
    EXAMS: 0 0 0 0 0 0 
    
    STUDENT: null
    ASSIGNMENTS: 0 0 0 0 0 0 0 0 0 
    EXAMS: 0 0 0 0 0 0 
    
    STUDENT: null
    ASSIGNMENTS: 0 0 0 0 0 0 0 0 0 
    EXAMS: 0 0 0 0 0 0 
    
    STUDENT: null
    ASSIGNMENTS: 0 0 0 0 0 0 0 0 0 
    EXAMS: 0 0 0 0 0 0 
    
    STUDENT: null
    ASSIGNMENTS: 0 0 0 0 0 0 0 0 0 
    EXAMS: 0 0 0 0 0 0 
    
    STUDENT: null
    ASSIGNMENTS: 0 0 0 0 0 0 0 0 0 
    EXAMS: 0 0 0 0 0 0 
    
    STUDENT: null
    ASSIGNMENTS: 0 0 0 0 0 0 0 0 0 
    EXAMS: 0 0 0 0 0 0 
    
    STUDENT: null
    ASSIGNMENTS: 0 0 0 0 0 0 0 0 0 
    EXAMS: 0 0 0 0 0 0 
    
    STUDENT: null
    ASSIGNMENTS: 0 0 0 0 0 0 0 0 0 
    EXAMS: 0 0 0 0 0 0 
    
    STUDENT: null
    ASSIGNMENTS: 0 0 0 0 0 0 0 0 0 
    EXAMS: 0 0 0 0 0 0 
    
    STUDENT: null
    ASSIGNMENTS: 0 0 0 0 0 0 0 0 0 
    EXAMS: 0 0 0 0 0 0 
    
    STUDENT: null
    ASSIGNMENTS: 0 0 0 0 0 0 0 0 0 
    EXAMS: 0 0 0 0 0 0 
    
    STUDENT: null
    ASSIGNMENTS: 0 0 0 0 0 0 0 0 0 
    EXAMS: 0 0 0 0 0 0 
    
    STUDENT: null
    ASSIGNMENTS: 0 0 0 0 0 0 0 0 0 
    EXAMS: 0 0 0 0 0 0 
    
    STUDENT: null
    ASSIGNMENTS: 0 0 0 0 0 0 0 0 0 
    EXAMS: 0 0 0 0 0 0 
    
    STUDENT: null
    ASSIGNMENTS: 0 0 0 0 0 0 0 0 0 
    EXAMS: 0 0 0 0 0 0 
    
    STUDENT: null
    ASSIGNMENTS: 0 0 0 0 0 0 0 0 0 
    EXAMS: 0 0 0 0 0 0 
    

    现在,它是如何工作的:

    main(String[]) 方法,它初始化Main 的一个新实例。

    Main 的构造函数中,调用parseResults(String fileName) 方法读取文件并解析结果。然后,调用printResults() 方法,您可以通过名称猜到,该方法会打印结果。

    parseResults() 方法: 这就是所有魔法发生的地方。它首先读取整个文件,然后逐行遍历它。如果它正在读取的行的行号是偶数,它将从该行中获取文本并将其附加到STUDENTS 数组的下一行。如果行号是奇数,它知道这一行包含最后一个学生的成绩,因此它调用getGrades() 方法,将一行成绩解析为一个整数数组,其中包含该行文本中的所有成绩,然后附加Grades 整数数组到GRADES 数组的下一行。

    【讨论】:

    • 非常感谢您的帮助,但这是使用一些我尚未涵盖的 Java 技术,因此无法在我的程序中使用。 (即缓冲区读取器、字符串读取器、级别和记录器)
    • @MattCariglio 如果你能告诉我你不能使用的所有“技术”,我可以修改应用程序吗?
    • 我不能使用 try & catch 语句来处理异常,只有方法头中的 throws 子句。没有数组列表。我仅限于使用一组指定的 4 种方法。完成所有文件处理并填充数组的 fillArray 方法。一种以预期格式显示学生姓名和成绩的显示方法。我必须创建另外 2 种方法来 (1) 计算并显示 5 次考试中每一次的班级平均成绩,以及 (2) 每个学生的班级平均成绩,我没有包含在我的代码中,因为它们在数组之前无法使用正确填写。
    【解决方案3】:

    使用Integer.parseInt(gradeFile.next()) 代替gradeFile.nextInt()

    它是这样工作的:

    /************* ERROR OCCURS HERE ********************/
    for (int j = 0; j < COLS; j++) {
    
        // Store the grade into the array's current index
        sGrades[i][j] = Integer.parseInt(gradeFile.next());
        /**************                       *******************/
    }
    
    if (gradeFile.hasNext())
        gradeFile.nextLine();
    

    【讨论】:

      【解决方案4】:

      试试这样的

      private static final int COLS = 15;
      
      public static void computeScores() throws IOException {
          int totalStudents = 0, totalMarks = 0;
          String[] lines = new String(Files.readAllBytes(Paths.get("data.txt"))).split("[\\r\\n]+");
          String[] sNames = new String[lines.length / 2];
          int[][] grades = new int[lines.length / 2][COLS];
          if (lines.length > 0) {
              for (int i = 0; i < lines.length; i++) {
                  if (i % 2 == 0) {
                      sNames[totalStudents] = lines[i];
                      totalStudents++;
                  } else {
                      String[] marks = lines[i].split("  ");
                      for (int j = 0; j < marks.length; j++)
                          grades[totalMarks][j] = Integer.parseInt(marks[j].trim());
                      totalMarks++;
                  }
              }
          }
      }
      
      //go ahead and print out your values the usual way you've been doing it
      
          for (int i = 0; i < totalStudents; i++) {
              System.out.println();
              //
              System.out.print("STUDENT: " + sNames[i]);
      
              System.out.print("\nASSIGNMENTS: ");
              //
              for (int j = 0; j < 10; j++)
                  //
                  System.out.print(grades[i][j] + " ");
      
              //
              System.out.print("\nEXAMS: ");
      
              //
              for (int k = 10; k < COLS; k++)
                  //
                  System.out.print(grades[i][k] + " ");
              System.out.println();
          }
      

      这应该打印得很好

      【讨论】:

        【解决方案5】:

        感谢大家的意见。我发现问题是处理学生姓名的不必要的for 循环。我在fillArray() 方法中修改了我的代码,如下所示:

        private static int fillArray(int[][] sGrades, String[] sNames) throws IOException
        {
            int students = 0;   // Students counter
        
            // Create the file
            File studentGrades = new File("Grades.txt");
        
            // Check that the file exists
            if (!studentGrades.exists())
            {
                // Display error message and exit the program
                System.out.println(studentGrades + " not found. Aborting.");
                System.exit(0);
            }
            // Create scanner object to read from the file
            Scanner gradeFile = new Scanner(studentGrades);
        
            // Read data until the end of the file is reached or array is full
            while (gradeFile.hasNext() && students < ROWS)
            {
                sNames[students] = gradeFile.nextLine();
        
                for ( int i = 0; i < COLS; i++ )
                    sGrades[students][i] = gradeFile.nextInt();
        
                students++;
                gradeFile.nextLine();
            }
        
            // Close the file
            gradeFile.close();
            // Return the total number of students
            return students;
        }
        

        瞧!

            STUDENT:     John, Elton
            ASSIGNMENTS: 89 97 91 94 82 96 98 67 69 97 
            EXAMS:       87 90 100 80 92 
        
            STUDENT:     Johnson, Kay
            ASSIGNMENTS: 96 68 71 70 90 79 69 63 88 75 
            EXAMS:       61 77 100 80 88 
        
            STUDENT:     Liston, Ed
            ASSIGNMENTS: 78 98 98 85 96 96 64 60 81 61 
            EXAMS:       66 83 100 98 93 
        
            STUDENT:     Kelly, Michael
            ASSIGNMENTS: 72 64 76 76 86 100 69 87 76 79 
            EXAMS:       76 93 100 78 82 
        
            STUDENT:     Presley, Elvis
            ASSIGNMENTS: 92 94 100 50 82 79 72 75 78 85 
            EXAMS:       70 76 100 87 79 
        
            STUDENT:     Hughes, Meghan
            ASSIGNMENTS: 90 97 89 100 94 88 70 92 90 92 
            EXAMS:       91 84 100 94 71 
        
            STUDENT:     Madonna
            ASSIGNMENTS: 97 97 84 94 96 91 86 95 90 98 
            EXAMS:       93 91 100 98 96 
        
            STUDENT:     Pacino, Al
            ASSIGNMENTS: 73 71 77 70 89 100 82 0 90 77 
            EXAMS:       5 77 100 80 74 
        
            STUDENT:     Bush, George W.
            ASSIGNMENTS: 76 73 60 82 79 74 66 77 73 86 
            EXAMS:       70 78 100 77 90 
        
            STUDENT:     Burke, Maggie
            ASSIGNMENTS: 94 73 74 79 66 78 43 90 97 91 
            EXAMS:       87 79 100 67 90 
        
            STUDENT:     Diesel, Vin
            ASSIGNMENTS: 60 64 89 66 52 70 67 66 67 66 
            EXAMS:       55 73 100 75 45 
        
            STUDENT:     Spiderman
            ASSIGNMENTS: 89 75 91 99 91 80 100 98 91 78 
            EXAMS:       92 93 100 92 99 
        
            STUDENT:     Baggins, Bilbo
            ASSIGNMENTS: 82 81 55 89 71 74 35 68 86 96 
            EXAMS:       65 0 100 71 61 
        
            STUDENT:     Williams, Serena
            ASSIGNMENTS: 100 94 96 98 90 90 92 91 92 90 
            EXAMS:       88 94 100 82 92 
        
            STUDENT:     Baggins, Frodo
            ASSIGNMENTS: 68 78 80 73 83 74 74 67 39 81 
            EXAMS:       65 88 100 68 92 
        
            STUDENT:     Potter, Harry
            ASSIGNMENTS: 87 61 78 89 86 80 70 72 77 83 
            EXAMS:       65 93 100 86 67 
        
            STUDENT:     Cianci, Buddy
            ASSIGNMENTS: 98 70 60 91 67 81 89 64 70 77 
            EXAMS:       62 77 100 92 76 
        
            STUDENT:     Basilico, Anthony
            ASSIGNMENTS: 67 69 76 76 75 67 83 83 88 75 
            EXAMS:       63 63 100 82 100 
        
            STUDENT:     Clapton, Eric
            ASSIGNMENTS: 100 85 64 89 83 68 84 91 84 66 
            EXAMS:       81 84 100 100 95 
        
            STUDENT:     Lennon, John
            ASSIGNMENTS: 88 65 84 68 80 90 61 62 88 75 
            EXAMS:       74 75 100 80 76 
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-02-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多