读取文本文件并创建二维数组

时间:2018-11-24 23:50:04

标签: java arrays

我有一个文本文件,其中包括学生的名字和成绩。我正在尝试阅读成绩并将其放入另一个方法的2d数组中,然后我想在main方法中调用它以打印出数组。但是,如果我用自己的方法调试代码,则可以打印所有内容,但是如果在main方法中调用它,则仅打印数组的最后一行。你们能告诉我我在这里想念什么吗?

非常感谢您的帮助。

这是我的文本文件:

John  25 5 4.5 5 4 5 10 10 6 9.5 5.5
Jim   25 5 4 5 4.5 5 10 4 10 9.5 7.5
Kathy 15 1 3 2 1 1.5 8 2 4 3 4
Steve 21 5 3 2 1 4 5 6 7 8 8
Stacy 15 5 1 1 1 5 3 8 9 5 7
Faith 16 3 4 2 4 4 7 5 2 3 8

这是我的方法

    public static double[][] processGrades(double[][] grade) throws IOException 
{       
    PrintWriter writer = new PrintWriter(new FileOutputStream("Output.txt"));

        Scanner readNum = null;
        Scanner scan =  null;
        int count = 0;
        int count2 = 0;   
        int width = 0;              
        String[] col = null;                
        String[][] tempGrade = null; 
        String line = null;
        String line2 = null;
        String[] newline = null;
        int maxInLine = 0;

        try
        {           
             //Create Grades Array

             scan = new Scanner(new FileInputStream("input.txt"));

             scan.nextLine();

             while(scan.hasNext())
             {
                line2 = scan.nextLine();    
                col = line2.split(" ");
                width = col.length;
                count++;    

                System.out.println(col.length);
             }

             tempGrade = new String[count][width];          
             grade = new double[count][width];

             readNum =  new Scanner(new FileInputStream("input.txt"));

             readNum.nextLine();

             //fill Grades array
             for (int i = 0; i < grade.length && readNum.hasNextLine(); i++) 
             {              
                   for (int j = 0; j < grade.length && readNum.hasNextLine(); j++) 
                   {    
                           tempGrade[i][j] = readNum.nextLine();    

                           String tempNum = tempGrade[i][j].replaceAll("[^0-9.0 +$]","");

                            // get the lines

                            String[] lines = tempNum.split("\\r?\\n");

                            // get the max amt of nums in a single line

                            for (String x : lines)                        
                            {
                                String[] temp = x.split("\\s+"); 

                                // split on whitespace
                                if (temp.length > maxInLine) 
                                {
                                    maxInLine = temp.length;    

                                }
                            }

                            String[][] array = new String[lines.length][maxInLine]; // declare and instantiate the array of arrays

                            for (int o = 0; o < lines.length; o++) 
                               {    
                                // split on whitespace
                                   String[] temp = lines[o].split("\\s+"); 

                                        for (int f = 1; f < maxInLine; f++) 
                                        {
                                            array[o][f] = (temp[f]);

                                            grade[o][f] = Double.parseDouble(array[o][f]);


                                        }                   
                               }    

                       }    

                }

            readNum.close();
            scan.close();
            writer.close();

        }

        catch(FileNotFoundException e)
        {
            System.out.println("File Not Found");

        }

        return grade;  
}


public static void main(String[] args) throws IOException, ParseException 
{

    PrintWriter writer = new PrintWriter(new FileOutputStream("Output.txt"));

    String[] names = null;
    double[][] grades = null;   
    double[][] grade = null;
    double[][] min =null;
    double[][] max =null;
    double average =0;

    grades = processGrades(grade);

    for(int i=0; i < grades.length; i++)
    {
        for(int j=0; j < grades[i].length; j++)
        {
            System.out.println(grades[i][j]);
        }
    }

    writer.close();

}

如您所见,仅打印最后一组成绩,其余显示为0。 输出:

16.0
3.0
4.0
2.0
4.0
4.0
7.0
5.0
2.0
3.0
8.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0

如果帖子的格式难以阅读或不正确,请原谅我。这是我第一次发帖,不确定要做什么。谢谢

2 个答案:

答案 0 :(得分:1)

我必须对双数组的大小进行硬编码,并且它可以工作。这是我更新的解决方案。

public static void main(String[] arg) throws IOException {
    double[][] grades = null;
    double[][] gradelist = Grade(grades);

    for(int i=0; i < gradelist.length; i++) {
        for(int j=0; j < gradelist[i].length; j++) {
            System.out.println(gradelist[i][j]);
        }
    }
}

public static double[][]Grade(double[][]grade) {
    Scanner in  = null;
    try {
        in = new Scanner(new FileInputStream("input.txt"));         
        in.nextLine();

          int rows = 6;
          int columns = 12;

          grade = new double[rows][columns];

          while(in.hasNextLine())  {
             for (int i=0; i< grade.length; i++) {
                String[] line = in.nextLine().trim().split(" ");
                for (int j = 1; j < line.length; j++) {
                   grade[i][j] = Double.parseDouble((line[j]));
                }
             }
          }
    }
    catch(Exception e) {
    }

    return grade;
}

答案 1 :(得分:0)

我建议您考虑采用以下方法。它与您当前的代码相去甚远,但我认为它更干净:

  

1)创建一个构造学生的课程

public class Student {
private String name;
private List<Double> grades; // can be a list of int depending on what you need

public Student(String name) {
    this.name = name;
    grades = new ArrayList<Double>();
}

public void setGrade(Double grade) {
    grades.add(grade);
}


@Override
private String toString() {
    //Override what is automatically printed when you call Student.toString() to print
}
}

在这里,我们创建了一个学生抽象。

  

2)一种不同的文件读取方法:

public static List<Student> load(String file) throws IOException {
    List<Student> students = new ArrayList<Student>();
    List<String> lines = Files.readAllLines(Paths.get(file));
    for (String line : lines) {
        if (!line.isEmpty()) {
            ArrayList<String> partsOfLine = splitOnSpace(line);
            Student s = new Student(partsOfLine.get(0));
            /* Here, if the number of grades is consistently n, simply use
               s.setGrade(partsOfLine.get(1));
               .
               . 
               s.setGrade(partsOfLine.get(n));
            if not, use some sort of looping to set all grades */
            students.add(s)
        }
    }
return students; // This arrayList can be passed to your print method
}

 public static ArrayList<String> splitOnSpace(String line){
        String[] splits = line.split(" ");
        return new ArrayList<>(Arrays.asList(splits));
}
  

3)主体中的示例打印方法

public void print(List<Students> students){
for (Student s: students) {
    System.out.println(s.toString());
}
}