Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JAVA-Read.txt文件,混合字符串和;整数,将字符串存储在数组中,将整数存储在二维数组中_Java_Arrays_String_File_Int - Fatal编程技术网

JAVA-Read.txt文件,混合字符串和;整数,将字符串存储在数组中,将整数存储在二维数组中

JAVA-Read.txt文件,混合字符串和;整数,将字符串存储在数组中,将整数存储在二维数组中,java,arrays,string,file,int,Java,Arrays,String,File,Int,我有一个文本文件,其中一行是学生姓名,下一行是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...) 我需要

我有一个文本文件,其中一行是学生姓名,下一行是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...)

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

因为程序在我看到任何输出之前就崩溃了,所以我删除了下面一行代码,该代码试图读取下一个整数以查看发生了什么

    for ( int j = 0; j < COLS; j++ )
        sGrades[i][j] = gradeFile.nextInt();
当我试图找出我的错误时,我的大脑很痛。如果我猜的话,我会认为这与分隔每个整数的空格有关,导致每一行分数被解释为字符串而不是整数。或者是我忽略了什么

编辑:我仅限于为这个程序使用更基本的Java技术。除了在方法头中使用
抛出
子句之外,我不能使用数组列表和异常处理。文件处理仅限于使用
文件
扫描仪
类。无
BufferReader
StringReader
FileReader
使用
Integer.parseInt(gradeFile.next())
而不是
gradeFile.nextInt()

它的工作原理如下:

    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...)
    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...)
/************* 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();
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;
}
/**********此处发生错误********************/
对于(int j=0;j
使用
Integer.parseInt(gradeFile.next())
而不是
gradeFile.nextInt()

它的工作原理如下:

    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...)
    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...)
/************* 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();
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;
}
/**********此处发生错误********************/
对于(int j=0;j
在填充过程中,请使用以下try-and-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){

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

用try-and-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){

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

好吧,我已经写了一个应用程序来做你想做的事情

这是:

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;
    }
}
最后,这是输出:

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(字符串文件名)
方法,该方法读取文件并解析结果。然后,调用
printResults()
方法,您可以通过名称猜出,该方法将打印结果

解析结果()方法:

这就是所有魔法发生的地方。它首先读取整个文件,然后逐行迭代。如果它读取的行的行号是偶数,它将从该行中提取文本,并将其附加到
STUDENTS
数组的下一行。如果行号是奇数,它知道此行保存最后一个学生的成绩,因此它调用
getGrades()
方法,该方法将一行成绩解析为一个整数数组,该数组保存文本行中的所有成绩,然后,它将grades整数数组追加到
grades
数组的下一行。

我已经编写了一个应用程序来精确地执行您想要的操作

这是:

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;
    }
}
最后,这是输出:

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(字符串文件名)
方法,该方法读取文件并解析结果。然后,调用
printResults()
方法,您可以通过名称猜出,该方法将打印结果

解析结果()方法:
这就是所有魔法发生的地方。它首先读取整个文件,然后逐行迭代。如果所读行的行号是偶数,它将从该行中提取文本并将其附加到
学生
阵列的下一行