I'm having trouble working around an ArithmeticException I'm getting from my getAverageScore() method in my Student class. I'm trying to write a program that reads the following text file scores.txt:
34 c081 c082 c083 c084
S2023 99 75 85 62
S2025 -1 92 67 52
S1909 100 83 45 -1
The c numbers such as c081 are course codes at the school, and the s numbers such as s2023 are student numbers. The figures in the middle represent their scores, the -1 also means they weren't enrolled in the unit.
I want to be able to write a program where I can give output as the student with the highest average across their classes, with that average and their student number. I want to be able to make sure the -1 values aren't included in that class average, so that if a student has one of those, their average is only calculated for the classes they did actually take.
This is the Student class:
import java.util.ArrayList;
public class Student {
private String studentNumber;
private ArrayList<Integer> scores = new ArrayList<Integer>();
public Student(String studentText) {
String[] parts = studentText.split(studentText, ' ');
this.studentNumber = parts[0];
for (int i = 1; i < parts.length - 1; i++) {
scores.add(Integer.parseInt(parts[i + 1]));
}
}
public String getStudentNumber() {
return this.studentNumber;
}
public float getAverageScore() {
int sum = 0;
int numberOfCoursesNotTaken = 0;
for (int i = 0; i <this.scores.size(); i++) {
if (i != -1) {
sum += this.scores.get(i);
System.out.println(sum);
} else {
numberOfCoursesNotTaken++ ;
System.out.println(numberOfCoursesNotTaken);
}
}
return sum / (this.scores.size() - numberOfCoursesNotTaken);
}
}
I'm calling this method from the following class:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class MySchool {
public static void main(String[] args) {
int numberOfStudents;
ArrayList<Student> allStudents = new ArrayList<Student>() ;
try {
File scoresFile = new File("Scores.txt");
Scanner scoresFileReader = new Scanner(scoresFile);
String headerRow = scoresFileReader.nextLine();
char c = headerRow.charAt(0);
numberOfStudents = Character.getNumericValue(c);
for (int studentI = 0; studentI < numberOfStudents; studentI++) {
String studentText = scoresFileReader.nextLine();
System.out.println(studentText);
Student student = new Student(studentText);
allStudents.add(student);
}
scoresFileReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred");
e.printStackTrace();
}
float highestAverage = 0;
String highestScoringStudentNumber = null;
for (Student student : allStudents) {
if (student.getAverageScore() > highestAverage) {
highestAverage = student.getAverageScore();
highestScoringStudentNumber = student.getStudentNumber();
}
}
System.out.println("Highest scoring student: " + highestScoringStudentNumber);
}
}
However, the return line of getAverageScore() in Student gives the following error: Exception in thread "main" java.lang.ArithmeticException: / by zero
at Student.getAverageScore(Student.java:34)
at MySchool.main(MySchool.java:42)
I thought I'd solved this issue using the numberOfCoursesNotTaken variable? Could anyone help me?
I really recommend removing invalid values as soon as they are found. You could replace your Student constructor by the following:
public Student(String studentText) {
String[] parts = studentText.split(" "); // previously (studentText, ' ')
this.studentNumber = parts[0];
for (int i = 1; i < parts.length - 1; i++) {
int score = Integer.parseInt(parts[i]); // NOT i+1
if (score >=0) this.scores.add(score);
}
}
While you are at it, you can greatly simplify your average-score calculation (now that there are no -1s):
public float averageScore() {
if (scores.isEmpty()) {
return 0; // avoids divide-by-zero
} else {
int total = 0;
for (int score : scores) total += score;
return total / (float) scores.size();
}
}
Student class -> getAverageScore : in the for loop, you're checking if i != -1, instead of if scores.get(i) != -1.
Related
I'm trying to write a program to read a file called scores.txt where it prints out the ID of the student with the highest average across their courses along with their student ID.
This is what scores.txt looks like:
34 c081 c082 c083 c084
S2023 99 75 85 62
S2025 -1 92 67 52
S1909 100 83 45 -1
So basically, the 34 a the beginning is a 3 for the number of students and a 4 for the number of courses (yes, I know this is silly, but the file was provided for my task). The c numbers such as c081 are course codes at the school, and the s numbers such as s2023 are student numbers. The figures in the middle represent their scores, the -1 also means they weren't enrolled in the unit.
Anyway, so far I've written a MySchool class and a Student class, which I'll paste below:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class MySchool {
public static void main(String[] args) {
int numberOfStudents;
ArrayList<Student> allStudents = new ArrayList<Student>() ;
// grab first line only, and check if first target is integer, or string
try {
File scoresFile = new File("Scores.txt");
Scanner scoresFileReader = new Scanner(scoresFile);
String headerRow = scoresFileReader.nextLine();
numberOfStudents = headerRow.charAt(0);
while(scoresFileReader.hasNextLine()) {
for (int studentI = 0; studentI < numberOfStudents; studentI++) {
String studentText = scoresFileReader.nextLine();
System.out.println(studentText);
Student student = new Student(studentText);
allStudents.add(student);
}}
scoresFileReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred");
e.printStackTrace();
}
float highestAverage = 0;
String highestScoringStudentNumber = null;
for (Student student : allStudents) {
if (student.getAverageScore() > highestAverage) {
highestAverage = student.getAverageScore();
highestScoringStudentNumber = student.getStudentNumber();
}
}
System.out.println("Highest scoring student: " + highestScoringStudentNumber);
}
}
import java.util.ArrayList;
public class Student {
private String studentNumber;
private ArrayList<Integer> scores = new ArrayList<Integer>();
public Student(String studentText) {
String[] parts = studentText.split(studentText, ' ');
this.studentNumber = parts[0];
for (int i = 1; i < parts.length - 1; i++) {
scores.add(Integer.parseInt(parts[i + 1]));
}
}
public String getStudentNumber() {
return this.studentNumber;
}
public float getAverageScore() {
int sum = 0;
for (int i = 0; i <this.scores.size(); i++) {
sum += this.scores.get(i);
}
return sum / this.scores.size();
}
}
Basically I want to be able to have an object for students where they have their student number and their scores. This is so that I can give them an average.
However, it seems that I've done something wrong in reading the file in (Haven't ever done this before), because the String studentText = scoresFileReader.nextLine(); line throws me an error that states : Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
at MySchool.main(MySchool.java:22)
If it's any help, the three student codes and their scores print out the way they should before I get this error.
Can anyone help me to get this up and running? I'm not sure how to resolve it
EDIT:
I've actually noticed the issue to be that somehow numberOfStudents is being set to 51 when there's no 51 in the data. Even if I run the code below, it prints the first value of headerRow confirming that it is 3, which is correct. The when I use the same code to assign it to numberOfStudents suddenly it's become 51 when it prints again?
import java.io.File; // Import the File class
import java.io.FileNotFoundException; // Import this class to handle errors
import java.util.ArrayList;
import java.util.Scanner; // Import the Scanner class to read text files
public class MySchool {
public static void main(String[] args) {
int numberOfStudents;
ArrayList<Student> allStudents = new ArrayList<Student>() ;
// grab first line only, and check if first target is integer, or string
try {
File scoresFile = new File("Scores.txt");
Scanner scoresFileReader = new Scanner(scoresFile);
String headerRow = scoresFileReader.nextLine();
System.out.println(headerRow.charAt(0));
numberOfStudents = headerRow.charAt(0);
System.out.println(numberOfStudents);
for (int studentI = 0; studentI < numberOfStudents; studentI++) {
String studentText = scoresFileReader.nextLine();
System.out.println(studentText);
Student student = new Student(studentText);
allStudents.add(student);
}
scoresFileReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred");
e.printStackTrace();
}
float highestAverage = 0;
String highestScoringStudentNumber = null;
for (Student student : allStudents) {
if (student.getAverageScore() > highestAverage) {
highestAverage = student.getAverageScore();
highestScoringStudentNumber = student.getStudentNumber();
}
}
System.out.println("Highest scoring student: " + highestScoringStudentNumber);
}
}
The problem comes from the fact that you're actually reading an ASCII code of the char, not the value itself - '3' == 51. You need to convert the character to the correct value. The simpliest way is to use Character.getNumericValue(), eg.:
char c = headerRow.charAt(0);
numberOfStudents = Character.getNumericValue(c);
I'm new to using array lists and would like to ask why I am getting an index out of bounds exception when I explicitly state that my students array list must be larger than zero before trying to access it in my if statement on line 23.
I am not sure what I am doing wrong and could really use some help.
Thank you.
My code:
import java.util.Scanner;
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Student> students = new ArrayList<Student>();
String name = "";
int age = 0;
int GPA = 0;
boolean running = true;
while(running) {
name = input.next();
if(name.equals("next") && students.size() > 0) {
students.remove(0);
continue;
} else if(name.equals("end")) {
running = false;
}
age = input.nextInt();
GPA = input.nextInt();
Student newStudent = new Student(name, age, GPA);
if(students.size() > 0 && age < students.get(students.size() - 1).getAge() || GPA < students.get(students.size() - 1).getGPA()) {
String tempName = students.get(students.size() - 1).getName();
int tempAge = students.get(students.size() - 1).getAge();
int tempGPA = students.get(students.size() - 1).getGPA();
Student tempStudent = new Student(tempName, tempAge, tempGPA);
students.remove(students.size() - 1);
students.add(newStudent);
students.add(tempStudent);
} else {
students.add(newStudent);
}
}
if(students.size() == 0) {
System.out.println("empty");
} else {
for(int i = 0; i < students.size(); i++) {
System.out.println(students.get(i).getName());
}
}
}
}
The array is zero based (the items are indexed 0,1,2,3...n-1 where n is the number of items), so students.get(students.size()) will always fail with an out-of-bounds. It should be students.get(students.size()-1).
you als should not use while(true) if possible, because its not so elegant. Rather state the condition to continue in brackets.
Are "while(true)" loops so bad?
Update: Thank you so much for all your input! I figured out that my low returns all 0s because java initializes all integers 0 so I changed it to int lowScore [] = new int [] {100, 100, 100, 100, 100}. The problem with findAvg is that in main i created an array of student [40] but the file only contains 15 students, which is why I cannot use a.length to find average. I've added codes to count the number of lines.
I am working on an assignment about reading a txt file of student ID along with their 5 quiz scores. The assignment is asking to read those scores up to 40 students and calculate the high, low and average for each quiz.
Sample output:
Stud Quiz1 Quiz2 Quiz3 Quiz4 Quiz5
1234 90 100 90 98 80
1243 92 92 90 98 70
High Score: 92 100 90 98 80
Low Score: 90 92 90 98 70
Average Score: 91 96 90 98 75
I've created 4 classes: student class for ID and scores, statistics class to calculate high, low and average, util class for read file function, and driver class for the main.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;
class Student {
private int SID;
private int scores[] = new int[5];
public int getSID() {
return SID;
}
public void setSID(int sID) {
SID = sID;
}
public int getScores(int index) {
return scores[index];
}
public void setScores(int[] scores) {
this.scores = scores;
}
public void printSID() {
System.out.println(SID);
}
public void printScores() {
for (int x : scores) {
System.out.println(x);
}
}
}
class Statistics {
private final int[] lowscores = new int[5];
private final int[] highscores = new int[5];
private final float[] avgscores = new float[5];
public void findlow(Student[] a) {
for (Student stu : a) {
for (int i = 0; i < 5; i++) {
lowscores[i] = Math.min(lowscores[i], stu.getScores(i));
}
}
}
public void findhigh(Student[] a) {
for (Student stu : a) {
for (int i = 0; i < 5; i++) {
highscores[i] = Math.max(highscores[i], stu.getScores(i));
}
}
}
public void findavg(Student[] a) {
int[] sum = new int[5];
for (Student stu : a) {
for (int i = 0; i < 5; i++) {
sum[i] += stu.getScores(i);
avgscores[i] = sum[i] / a.length;
}
}
}
public void printLow() {
for (int x : lowscores) {
System.out.println("Low Score " + x);
}
}
public void printHigh() {
for (int x : highscores) {
System.out.println("High Score " + x);
}
}
public void printAvg() {
for (float x : avgscores) {
System.out.println("Average " + x);
}
}
}
class Util {
static Student[] readFile(String filename, Student[] stu) {
try {
FileReader file = new FileReader(filename);
BufferedReader buff = new BufferedReader(file);
int count = 0;
boolean eof = false;
while (!eof) {
String line = buff.readLine();
if (line == null)
break;
else {
System.out.println(line);
if (count > 0) {
StringTokenizer st = new StringTokenizer(line);
for (int i = 0; i < stu.length; i++) {
stu[i] = new Student();
}
stu[count - 1].setSID(Integer.parseInt(st.nextToken()));
int scores[] = new int[5];
int scoreCount = 0;
while (st.hasMoreTokens()) {
scores[scoreCount] = Integer.parseInt(st.nextToken());
scoreCount++;
stu[count - 1].setScores(scores);
}
}
}
count++;
}
buff.close();
} catch (IOException e) {
System.out.println("Error -- " + e.toString());
}
return stu;
}
}
public class Driver{
public static void main(String[] args) {
Student lab4[] = new Student[40];
lab4 = Util.readFile("C:\\lab4.txt", lab4);
Statistics statlab4 = new Statistics();
statlab4.findlow(lab4);
statlab4.findhigh(lab4);
statlab4.findavg(lab4);
statlab4.printLow();
statlab4.printHigh();
statlab4.printAvg();
}
}
The program reads an input file lab4.txt which includes 1 line of header and 15 lines of student records. The program runs but does not calculate the high low and average correctly. I know my calculation for average might be wrong; but I don't know why high and low don't work.
Please help me. Thank you!
For the find average, you shouldn't divide by a.length every iteration.
public void findavg(Student []a) {
int []sum = new int [5];
for(Student stu: a) {
for(int i=0; i<5; i++) {
sum[i] += stu.getScores(i);
}
}
for(int i=0; i<5; i++) {
avgscores[i] = sum[i] / a.length;
}
}
The min and max seems fine.
Not going to rewrite your code for you, just going to ask some questions because I think some people are still a bit confused about your purpose:
Is the purpose of the findAvg method to find the average of all the students marks for a particular test? Or to find the student's average mark for all of their tests?
Moving the Statistics class inside the methods of the Student class (as done by some of the other answers) would work if the latter is your goal, but I wouldn't mind keeping them separate if you're going for the former.
If you're trying to find the highest mark of a group of students, then I'd get them all into an Array or ArrayList and then try an ascending sort (or do them both at the same time).
public float avgCalculate(Student [] a, int testnumber){
float sum = 0.0f;
for (Student s: a){
sum = sum + s.getScores[testnumber];
}
float average = (sum / a.length);
return average;
}
Code is completely untested, so make sure it works and get back to me. It should calculate the average scores of a bunch of students (a) on a specific test (test number). Hopefully you can extrapolate the rest of the code (you may need to modify your other classes a bit etc.) For the highs and lows consider using the Arrays.sort() library method.
Since you've mentioned the Statistics class is required, I've taken another crack at your issue. And I see that when you calculate the highs and lows, the first loop is the students. Instead, make the first loop for the appropriate array, like so:
public void findLow(Student[] a) {
for (int i = 0; i < 5; i++)
for (Student stu : a)
lowScores[i] = Math.min(stu.getScore(i), lowScores[i]);
}
What this then does is:
for each low score you want to find:
for each student that took the quiz:
if this student's score is lower, set that as the lowest
Apply the same logic to your findHigh method.
For your findAvg method, as previously stated, don't divide in every iteration:
public void findAvg(Student[] a) {
for (int i = 0; i < 5; i++) {
for (Student s : a) {
avgScores[i] += s.getScore(i);
}
avgScores[i] /= a.length;
}
}
I am new to Java and I needed dynamic Array ... all of thing I found that's for dynamic Array we should use "Array List' that's ok but when I want the indexes to be the power of X that given from input , I face ERORR ! .. the indexes are unclear and the are not specified what is the first or 2th power ! .... can anyone help me how solve it?
public static void main(String[] args) throws Exception {
Scanner Reader = new Scanner(System.in);
ArrayList<Float> Zarayeb = new ArrayList<Float>();
Float s ;
int m;
System.out.print("Add Count of equation Sentences : ");
int N = Reader.nextInt();
if (N == 0)
return;
for (int i = 0; i < N ; i++) {
s = Reader.nextFloat() ;
System.out.print("x^");
m = Reader.nextInt();
if (Zarayeb.get(m)== null)
Zarayeb.add(0 , s);
else{
Float l ;
l = Zarayeb.get(m);
Zarayeb.add (m , l+s);
}
if (i < N-1)
System.out.print("\r+");
}
System.out.print("Add Count of equation Sentences : ");
N = Reader.nextInt();
if (N == 0)
return;
for (int i = 0; i < N ; i++) {
s = Reader.nextFloat() ;
System.out.print("x^");
m = Reader.nextInt();
if (Zarayeb.get(m)== null)
Zarayeb.add(m , s);
else{
Float l ;
l = Zarayeb.get(m);
Zarayeb.add (m , l+s);
}
if (i < N-1)
System.out.print("\r+");
}
System.out.print("Enter X: ");
float X = Reader.nextFloat();
float Sum = 0;
for (int i = 0; i < Zarayeb.size();i++) {
Sum += (Zarayeb.get(i) * Math.pow(X,i));
}
System.out.println("\nThe final answer is : " + Sum);
First I refactored your code a bit to make sense of it:
Main class with the top level logic:
import java.util.Scanner;
public class Main {
private Scanner scanner;
private final Totals totals = new Totals();
public static void main(final String[] args) {
final Main app = new Main();
app.run();
}
private void run() {
scanner = new Scanner(System.in);
try {
readAndProcessEquationSentences();
} finally {
scanner.close();
}
}
private void readAndProcessEquationSentences() {
readSentences(true);
readSentences(false);
System.out.println("The final answer is : " + totals.calculateSum(readBaseInput()));
}
private void readSentences(final boolean useInitialLogic) {
System.out.print("Enter number of equation sentences:");
final int numberOfSentences = scanner.nextInt();
if (numberOfSentences == 0) {
throw new RuntimeException("No sentences");
}
for (int i = 0; i < numberOfSentences; i++) {
Sentence sentence = Sentence.read(scanner);
if (useInitialLogic) {
totals.addInitialSentence(sentence);
} else {
totals.addNextSentence(sentence);
}
if (i < numberOfSentences - 1) {
System.out.print("\r+");
}
}
}
private float readBaseInput() {
System.out.print("Enter base: ");
return scanner.nextFloat();
}
}
Sentence class which represents one equation sentence entered by the user:
import java.util.Scanner;
public class Sentence {
private Float x;
private int y;
public static Sentence read(final Scanner scanner) {
final Sentence sentence = new Sentence();
System.out.println("Enter x^y");
System.out.print("x=");
sentence.x = scanner.nextFloat();
System.out.println();
System.out.print("y=");
sentence.y = scanner.nextInt();
System.out.println();
return sentence;
}
public Float getX() {
return x;
}
public int getY() {
return y;
}
}
Totals class which keeps track of the totals:
import java.util.ArrayList;
import java.util.List;
public class Totals {
private final List<Float> values = new ArrayList<Float>();
public void addInitialSentence(final Sentence sentence) {
if (values.size() <= sentence.getY()) {
addToStart(sentence);
} else {
addToValue(sentence);
}
}
private void addToStart(final Sentence sentence) {
values.add(0, sentence.getX());
}
public void addNextSentence(final Sentence sentence) {
if (values.size() <= sentence.getY()) {
values.add(sentence.getY(), sentence.getX());
} else {
addToValue(sentence);
}
}
private void addToValue(final Sentence sentence) {
Float total = values.get(sentence.getY());
total = total + sentence.getX();
values.add(sentence.getY(), total);
}
public float calculateSum(final float base) {
float sum = 0;
for (int i = 0; i < values.size(); i++) {
sum += (values.get(i) * Math.pow(base, i));
}
return sum;
}
}
I don't have the foggiest idea what this is supposed to do. I named the variables according to this foggy idea.
You are letting the user input values in two separate loops, with a slightly different logic I called 'initial' and 'next'.
In the initial loop you were doing this:
if (Zarayeb.get(m) == null)
Zarayeb.add(0 , s);
In the next loop this:
if (Zarayeb.get(m) == null)
Zarayeb.add(m , s);
There are problems with this because the ArrayList.get(m) will throw an IndexOutOfBoundException if m is out or range. So I changed that to the equivalent of:
if (Zarayeb.size() <= m) {
....
}
However, in the 'next' case this still does not solve it. What should happen in the second loop when an 'm' value is entered for which no element yet exists in the ArrayList?
Why do you need to enter sentences in two loops?
What is the logic supposed to achieve exactly?
I have a 2D Array called sectionArray which is of type Student class. Each student has a name and an array[] of 5 grades for exam scores. These names and scores are divided into to sections in a file that must be read. I keep getting a nullPointer on my sectionArray no matter what I change. Thank you for any suggestions.
import java.util.*;
import java.io.*;
public class ProgressReport {
private Student[][] sectionArray;// each student has a name,
// grade, average,
// and the array of scores
private File file;
private Scanner inputFile;
public ProgressReport() throws IOException {
sectionArray = new Student[2][];
file = new File("Lab5A.in.txt");
inputFile = new Scanner(file);
}
/**
*
* #return the values in the sectionArray
*/
public Student[][] getSectionArray() {
return sectionArray;
}
/**
* initialize sectionArray and set the values
*
* #param sectionArray
* passed 2D array of Students
*/
public void setSectionArray(Student[][] sectionArray) {
for (int i = 0; i < sectionArray.length; i++) {
for (int j = 0; j < sectionArray[i].length; j++) {
this.sectionArray[i][j] = sectionArray[i][j];
}
}
}
/**
* reads from the file and creates new Students
*
* #throws IOException
*/
public void readInputFile() throws IOException {
int colNum = 0;
int section = 0;
String name = " ";
int[] grades = new int[5];
while (inputFile.hasNext()) {
colNum = inputFile.nextInt();// gets size of row
sectionArray[section] = new Student[colNum];// initialize array
// iterates through colNum amount of times
for (int j = 0; j < colNum; j++) {
name = inputFile.next();// gets next name in column
for (int i = 0; i < 5; i++) {
// stores scores for that name
grades[i] = inputFile.nextInt();
}
// creates new Student with name and grades
sectionArray[section][j] = new Student(name, grades);
section++;
}
}
// passes the values in sectionArray
setSectionArray(sectionArray);
}
}
My student class looks like this:
public class Student {
private String name = " "; // Store the name of the student
private char grade; // Store the letter grade
private double average; // Store the average score
private int[] scores; // Store the five exam scores
public Student() {
grade = ' ';
average = 0.0;
}
public Student(String name, int[] score) {
this.name = name;
scores = new int[5];
for (int i = 0; i < scores.length; i++) {
scores[i] = 0;
}
for (int i = 0; i < scores.length; i++) {
this.scores[i] = score[i];
}
}
// getters
public String getName() {
return name;
}
public char getGrade() {
return grade;
}
public double getAverage() {
return average;
}
// think about changing this to return a different format
public int[] getScores() {
return scores;
}
// setters
public void setScore(int[] scores) {
}
public void setName(String name) {
this.name = name;
}
public void setGrade(char grade) {
this.grade = grade;
}
public void setAverage(double average) {
this.average = average;
}
/**
* determine the average of the five test scores for each student
*/
public void calculateAverage() {
double total = 0;
double average = 0;
for (int i = 0; i < scores.length; i++) {
total += scores[i];
}
average = total / scores.length;
setAverage(average);
}
/**
* Determine the student's letter grade based on average of test scores
*/
public void calculateGrade() {
double average = 0;
average = getAverage();
if (average <= 100 && average >= 90) {
setGrade('A');
} else if (average <= 89 && average >= 80) {
setGrade('B');
} else if (average <= 79 && average >= 70) {
setGrade('C');
} else if (average <= 69 && average >= 60) {
setGrade('D');
} else if (average <= 59 && average >= 0) {
setGrade('F');
}
}
public String toString() {
return getName() + " " + getAverage() + " " + getGrade();
}
}
The array you are trying to write is initialized with sectionArray = new Student[2][];. This will create a matrix (2D array) with 2 columns and only one row, and then you try to set your new values on this array. If you already know the size of the matrix you are going to read from the file, then initialize it with the correct values.
Anyway, I did not get why you are trying to use a 2D array for this. If I understood correctly the purpose of your code, you should be using a List instead to store the read data, and since it has a dynamically increasing size you wouldn't have to bother with controlling the indexes like you do with the array. Take a look at this tutorial to learn how to use lists.