Read text file and create a 2d array





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







-1















I have a text file which includes student names an grades. I am trying to read the grades and put them into a 2d array in a separate method, then I want to call it in the main method to print out the array. However, if I debug my code in its own method, I get everything print out, but if I call it in the main method, then only the last row of the array got printed out. Can you guys please tell me what am I missing here?



Thanks a lot for all your help.



This is my text file:



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




This is my method



    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();


}



As you can see, only the last set of grades is printed, the rest displayed as 0.
Output:



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




Please forgive me if the format of the post is hard to read or not right. This is my first time posting question, not sure what need to be done. Thanks










share|improve this question




















  • 1





    Sorry but... it's a mess :-) Use the reight abstractions. Use good names on things. Your file represents a list of students, which have grades. So use a List<Student>, where Student is a class with a name field of type String, and a grades field of type double. Split your code into small methods, doing simple things, like parsing one line into a Student, called in a loop by another method parsing all lines into a List<Student>. Declare variables only when you need them, and not all at the beginning of the method.

    – JB Nizet
    Nov 25 '18 at 0:00











  • Is it required that you use a standard array? You may have a better time if you consider using a collection of some sort.

    – hb22
    Nov 25 '18 at 0:23











  • @JB Nizet - I know it looks really long, but when I read the file, it seems the whole line get read as 1. I am trying to separate the string name with double grades but it won't work. The only way I can make it work and know how is to keep splitting the lines. If you know a better way, I would greatly appreciate the help. Thanks

    – Thi
    Nov 26 '18 at 19:34











  • @hb22 - I did not learn about collection yet.

    – Thi
    Nov 26 '18 at 19:35











  • You must split the lines. But you're not forced to put all the code in a giant method. As I said in my previous comment: you should have a separate method which parses (or splits, if you prefer) just one line and create a Student. And another one that loops through the lines and creates a list of students (or an array or students) by calling the first method for each line.

    – JB Nizet
    Nov 26 '18 at 19:39


















-1















I have a text file which includes student names an grades. I am trying to read the grades and put them into a 2d array in a separate method, then I want to call it in the main method to print out the array. However, if I debug my code in its own method, I get everything print out, but if I call it in the main method, then only the last row of the array got printed out. Can you guys please tell me what am I missing here?



Thanks a lot for all your help.



This is my text file:



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




This is my method



    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();


}



As you can see, only the last set of grades is printed, the rest displayed as 0.
Output:



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




Please forgive me if the format of the post is hard to read or not right. This is my first time posting question, not sure what need to be done. Thanks










share|improve this question




















  • 1





    Sorry but... it's a mess :-) Use the reight abstractions. Use good names on things. Your file represents a list of students, which have grades. So use a List<Student>, where Student is a class with a name field of type String, and a grades field of type double. Split your code into small methods, doing simple things, like parsing one line into a Student, called in a loop by another method parsing all lines into a List<Student>. Declare variables only when you need them, and not all at the beginning of the method.

    – JB Nizet
    Nov 25 '18 at 0:00











  • Is it required that you use a standard array? You may have a better time if you consider using a collection of some sort.

    – hb22
    Nov 25 '18 at 0:23











  • @JB Nizet - I know it looks really long, but when I read the file, it seems the whole line get read as 1. I am trying to separate the string name with double grades but it won't work. The only way I can make it work and know how is to keep splitting the lines. If you know a better way, I would greatly appreciate the help. Thanks

    – Thi
    Nov 26 '18 at 19:34











  • @hb22 - I did not learn about collection yet.

    – Thi
    Nov 26 '18 at 19:35











  • You must split the lines. But you're not forced to put all the code in a giant method. As I said in my previous comment: you should have a separate method which parses (or splits, if you prefer) just one line and create a Student. And another one that loops through the lines and creates a list of students (or an array or students) by calling the first method for each line.

    – JB Nizet
    Nov 26 '18 at 19:39














-1












-1








-1








I have a text file which includes student names an grades. I am trying to read the grades and put them into a 2d array in a separate method, then I want to call it in the main method to print out the array. However, if I debug my code in its own method, I get everything print out, but if I call it in the main method, then only the last row of the array got printed out. Can you guys please tell me what am I missing here?



Thanks a lot for all your help.



This is my text file:



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




This is my method



    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();


}



As you can see, only the last set of grades is printed, the rest displayed as 0.
Output:



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




Please forgive me if the format of the post is hard to read or not right. This is my first time posting question, not sure what need to be done. Thanks










share|improve this question
















I have a text file which includes student names an grades. I am trying to read the grades and put them into a 2d array in a separate method, then I want to call it in the main method to print out the array. However, if I debug my code in its own method, I get everything print out, but if I call it in the main method, then only the last row of the array got printed out. Can you guys please tell me what am I missing here?



Thanks a lot for all your help.



This is my text file:



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




This is my method



    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();


}



As you can see, only the last set of grades is printed, the rest displayed as 0.
Output:



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




Please forgive me if the format of the post is hard to read or not right. This is my first time posting question, not sure what need to be done. Thanks







java arrays






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 25 '18 at 0:01









JB Nizet

550k608981025




550k608981025










asked Nov 24 '18 at 23:50









ThiThi

207




207








  • 1





    Sorry but... it's a mess :-) Use the reight abstractions. Use good names on things. Your file represents a list of students, which have grades. So use a List<Student>, where Student is a class with a name field of type String, and a grades field of type double. Split your code into small methods, doing simple things, like parsing one line into a Student, called in a loop by another method parsing all lines into a List<Student>. Declare variables only when you need them, and not all at the beginning of the method.

    – JB Nizet
    Nov 25 '18 at 0:00











  • Is it required that you use a standard array? You may have a better time if you consider using a collection of some sort.

    – hb22
    Nov 25 '18 at 0:23











  • @JB Nizet - I know it looks really long, but when I read the file, it seems the whole line get read as 1. I am trying to separate the string name with double grades but it won't work. The only way I can make it work and know how is to keep splitting the lines. If you know a better way, I would greatly appreciate the help. Thanks

    – Thi
    Nov 26 '18 at 19:34











  • @hb22 - I did not learn about collection yet.

    – Thi
    Nov 26 '18 at 19:35











  • You must split the lines. But you're not forced to put all the code in a giant method. As I said in my previous comment: you should have a separate method which parses (or splits, if you prefer) just one line and create a Student. And another one that loops through the lines and creates a list of students (or an array or students) by calling the first method for each line.

    – JB Nizet
    Nov 26 '18 at 19:39














  • 1





    Sorry but... it's a mess :-) Use the reight abstractions. Use good names on things. Your file represents a list of students, which have grades. So use a List<Student>, where Student is a class with a name field of type String, and a grades field of type double. Split your code into small methods, doing simple things, like parsing one line into a Student, called in a loop by another method parsing all lines into a List<Student>. Declare variables only when you need them, and not all at the beginning of the method.

    – JB Nizet
    Nov 25 '18 at 0:00











  • Is it required that you use a standard array? You may have a better time if you consider using a collection of some sort.

    – hb22
    Nov 25 '18 at 0:23











  • @JB Nizet - I know it looks really long, but when I read the file, it seems the whole line get read as 1. I am trying to separate the string name with double grades but it won't work. The only way I can make it work and know how is to keep splitting the lines. If you know a better way, I would greatly appreciate the help. Thanks

    – Thi
    Nov 26 '18 at 19:34











  • @hb22 - I did not learn about collection yet.

    – Thi
    Nov 26 '18 at 19:35











  • You must split the lines. But you're not forced to put all the code in a giant method. As I said in my previous comment: you should have a separate method which parses (or splits, if you prefer) just one line and create a Student. And another one that loops through the lines and creates a list of students (or an array or students) by calling the first method for each line.

    – JB Nizet
    Nov 26 '18 at 19:39








1




1





Sorry but... it's a mess :-) Use the reight abstractions. Use good names on things. Your file represents a list of students, which have grades. So use a List<Student>, where Student is a class with a name field of type String, and a grades field of type double. Split your code into small methods, doing simple things, like parsing one line into a Student, called in a loop by another method parsing all lines into a List<Student>. Declare variables only when you need them, and not all at the beginning of the method.

– JB Nizet
Nov 25 '18 at 0:00





Sorry but... it's a mess :-) Use the reight abstractions. Use good names on things. Your file represents a list of students, which have grades. So use a List<Student>, where Student is a class with a name field of type String, and a grades field of type double. Split your code into small methods, doing simple things, like parsing one line into a Student, called in a loop by another method parsing all lines into a List<Student>. Declare variables only when you need them, and not all at the beginning of the method.

– JB Nizet
Nov 25 '18 at 0:00













Is it required that you use a standard array? You may have a better time if you consider using a collection of some sort.

– hb22
Nov 25 '18 at 0:23





Is it required that you use a standard array? You may have a better time if you consider using a collection of some sort.

– hb22
Nov 25 '18 at 0:23













@JB Nizet - I know it looks really long, but when I read the file, it seems the whole line get read as 1. I am trying to separate the string name with double grades but it won't work. The only way I can make it work and know how is to keep splitting the lines. If you know a better way, I would greatly appreciate the help. Thanks

– Thi
Nov 26 '18 at 19:34





@JB Nizet - I know it looks really long, but when I read the file, it seems the whole line get read as 1. I am trying to separate the string name with double grades but it won't work. The only way I can make it work and know how is to keep splitting the lines. If you know a better way, I would greatly appreciate the help. Thanks

– Thi
Nov 26 '18 at 19:34













@hb22 - I did not learn about collection yet.

– Thi
Nov 26 '18 at 19:35





@hb22 - I did not learn about collection yet.

– Thi
Nov 26 '18 at 19:35













You must split the lines. But you're not forced to put all the code in a giant method. As I said in my previous comment: you should have a separate method which parses (or splits, if you prefer) just one line and create a Student. And another one that loops through the lines and creates a list of students (or an array or students) by calling the first method for each line.

– JB Nizet
Nov 26 '18 at 19:39





You must split the lines. But you're not forced to put all the code in a giant method. As I said in my previous comment: you should have a separate method which parses (or splits, if you prefer) just one line and create a Student. And another one that loops through the lines and creates a list of students (or an array or students) by calling the first method for each line.

– JB Nizet
Nov 26 '18 at 19:39












2 Answers
2






active

oldest

votes


















1














I have to hard code the size for double array, and it works. This is my updated solution.



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 doubleGrade(doublegrade) {
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;
}





share|improve this answer


























  • Please accept the answer to help other people to find it in future.

    – Andrew Thompson
    Dec 5 '18 at 3:59



















0














I suggest you consider the following approach. It strays quite a bit from your current code but, in my opinion, is much cleaner:




1) Create a class that constructs a student




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
}
}


Here we have created a student abstraction.




2) A different file reading approach:




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) Sample print method in main




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





share|improve this answer
























  • @ht22 - I will give it a try and let you know. Thanks a lot for helping.

    – Thi
    Nov 26 '18 at 19:35













  • @ht22 - I tried your method and keep getting error on this line List<String> lines = Files.readAllLines(Paths.get(file)); I have to change to ArrayList<String> but then it doesn't return anything. I am able to figure out a different way to make it work. Thanks a lot for trying.

    – Thi
    Nov 27 '18 at 16:32













  • @Thi hmm, I am unable to reproduce this error. Anyways, glad you found a fix.

    – hb22
    Nov 27 '18 at 19:56











  • @ht22 - yes, I see so many post here using List<String> but I can't. I am using eclipse, not sure that's the cause.

    – Thi
    Nov 29 '18 at 22:00











  • @Thi List is higher in the collections hierarchy than ArrayList so make sure you are importing List instead of ArrayList. This way you can use either a List declaration or ArrayList. Be careful, though. Even if you declare a list you must instantiate it with something like an ArrayList.

    – hb22
    Feb 13 at 6:51












Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53463440%2fread-text-file-and-create-a-2d-array%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














I have to hard code the size for double array, and it works. This is my updated solution.



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 doubleGrade(doublegrade) {
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;
}





share|improve this answer


























  • Please accept the answer to help other people to find it in future.

    – Andrew Thompson
    Dec 5 '18 at 3:59
















1














I have to hard code the size for double array, and it works. This is my updated solution.



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 doubleGrade(doublegrade) {
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;
}





share|improve this answer


























  • Please accept the answer to help other people to find it in future.

    – Andrew Thompson
    Dec 5 '18 at 3:59














1












1








1







I have to hard code the size for double array, and it works. This is my updated solution.



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 doubleGrade(doublegrade) {
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;
}





share|improve this answer















I have to hard code the size for double array, and it works. This is my updated solution.



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 doubleGrade(doublegrade) {
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;
}






share|improve this answer














share|improve this answer



share|improve this answer








edited Dec 5 '18 at 3:58









Andrew Thompson

154k29166352




154k29166352










answered Nov 27 '18 at 16:36









ThiThi

207




207













  • Please accept the answer to help other people to find it in future.

    – Andrew Thompson
    Dec 5 '18 at 3:59



















  • Please accept the answer to help other people to find it in future.

    – Andrew Thompson
    Dec 5 '18 at 3:59

















Please accept the answer to help other people to find it in future.

– Andrew Thompson
Dec 5 '18 at 3:59





Please accept the answer to help other people to find it in future.

– Andrew Thompson
Dec 5 '18 at 3:59













0














I suggest you consider the following approach. It strays quite a bit from your current code but, in my opinion, is much cleaner:




1) Create a class that constructs a student




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
}
}


Here we have created a student abstraction.




2) A different file reading approach:




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) Sample print method in main




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





share|improve this answer
























  • @ht22 - I will give it a try and let you know. Thanks a lot for helping.

    – Thi
    Nov 26 '18 at 19:35













  • @ht22 - I tried your method and keep getting error on this line List<String> lines = Files.readAllLines(Paths.get(file)); I have to change to ArrayList<String> but then it doesn't return anything. I am able to figure out a different way to make it work. Thanks a lot for trying.

    – Thi
    Nov 27 '18 at 16:32













  • @Thi hmm, I am unable to reproduce this error. Anyways, glad you found a fix.

    – hb22
    Nov 27 '18 at 19:56











  • @ht22 - yes, I see so many post here using List<String> but I can't. I am using eclipse, not sure that's the cause.

    – Thi
    Nov 29 '18 at 22:00











  • @Thi List is higher in the collections hierarchy than ArrayList so make sure you are importing List instead of ArrayList. This way you can use either a List declaration or ArrayList. Be careful, though. Even if you declare a list you must instantiate it with something like an ArrayList.

    – hb22
    Feb 13 at 6:51
















0














I suggest you consider the following approach. It strays quite a bit from your current code but, in my opinion, is much cleaner:




1) Create a class that constructs a student




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
}
}


Here we have created a student abstraction.




2) A different file reading approach:




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) Sample print method in main




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





share|improve this answer
























  • @ht22 - I will give it a try and let you know. Thanks a lot for helping.

    – Thi
    Nov 26 '18 at 19:35













  • @ht22 - I tried your method and keep getting error on this line List<String> lines = Files.readAllLines(Paths.get(file)); I have to change to ArrayList<String> but then it doesn't return anything. I am able to figure out a different way to make it work. Thanks a lot for trying.

    – Thi
    Nov 27 '18 at 16:32













  • @Thi hmm, I am unable to reproduce this error. Anyways, glad you found a fix.

    – hb22
    Nov 27 '18 at 19:56











  • @ht22 - yes, I see so many post here using List<String> but I can't. I am using eclipse, not sure that's the cause.

    – Thi
    Nov 29 '18 at 22:00











  • @Thi List is higher in the collections hierarchy than ArrayList so make sure you are importing List instead of ArrayList. This way you can use either a List declaration or ArrayList. Be careful, though. Even if you declare a list you must instantiate it with something like an ArrayList.

    – hb22
    Feb 13 at 6:51














0












0








0







I suggest you consider the following approach. It strays quite a bit from your current code but, in my opinion, is much cleaner:




1) Create a class that constructs a student




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
}
}


Here we have created a student abstraction.




2) A different file reading approach:




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) Sample print method in main




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





share|improve this answer













I suggest you consider the following approach. It strays quite a bit from your current code but, in my opinion, is much cleaner:




1) Create a class that constructs a student




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
}
}


Here we have created a student abstraction.




2) A different file reading approach:




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) Sample print method in main




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






share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 25 '18 at 0:44









hb22hb22

191111




191111













  • @ht22 - I will give it a try and let you know. Thanks a lot for helping.

    – Thi
    Nov 26 '18 at 19:35













  • @ht22 - I tried your method and keep getting error on this line List<String> lines = Files.readAllLines(Paths.get(file)); I have to change to ArrayList<String> but then it doesn't return anything. I am able to figure out a different way to make it work. Thanks a lot for trying.

    – Thi
    Nov 27 '18 at 16:32













  • @Thi hmm, I am unable to reproduce this error. Anyways, glad you found a fix.

    – hb22
    Nov 27 '18 at 19:56











  • @ht22 - yes, I see so many post here using List<String> but I can't. I am using eclipse, not sure that's the cause.

    – Thi
    Nov 29 '18 at 22:00











  • @Thi List is higher in the collections hierarchy than ArrayList so make sure you are importing List instead of ArrayList. This way you can use either a List declaration or ArrayList. Be careful, though. Even if you declare a list you must instantiate it with something like an ArrayList.

    – hb22
    Feb 13 at 6:51



















  • @ht22 - I will give it a try and let you know. Thanks a lot for helping.

    – Thi
    Nov 26 '18 at 19:35













  • @ht22 - I tried your method and keep getting error on this line List<String> lines = Files.readAllLines(Paths.get(file)); I have to change to ArrayList<String> but then it doesn't return anything. I am able to figure out a different way to make it work. Thanks a lot for trying.

    – Thi
    Nov 27 '18 at 16:32













  • @Thi hmm, I am unable to reproduce this error. Anyways, glad you found a fix.

    – hb22
    Nov 27 '18 at 19:56











  • @ht22 - yes, I see so many post here using List<String> but I can't. I am using eclipse, not sure that's the cause.

    – Thi
    Nov 29 '18 at 22:00











  • @Thi List is higher in the collections hierarchy than ArrayList so make sure you are importing List instead of ArrayList. This way you can use either a List declaration or ArrayList. Be careful, though. Even if you declare a list you must instantiate it with something like an ArrayList.

    – hb22
    Feb 13 at 6:51

















@ht22 - I will give it a try and let you know. Thanks a lot for helping.

– Thi
Nov 26 '18 at 19:35







@ht22 - I will give it a try and let you know. Thanks a lot for helping.

– Thi
Nov 26 '18 at 19:35















@ht22 - I tried your method and keep getting error on this line List<String> lines = Files.readAllLines(Paths.get(file)); I have to change to ArrayList<String> but then it doesn't return anything. I am able to figure out a different way to make it work. Thanks a lot for trying.

– Thi
Nov 27 '18 at 16:32







@ht22 - I tried your method and keep getting error on this line List<String> lines = Files.readAllLines(Paths.get(file)); I have to change to ArrayList<String> but then it doesn't return anything. I am able to figure out a different way to make it work. Thanks a lot for trying.

– Thi
Nov 27 '18 at 16:32















@Thi hmm, I am unable to reproduce this error. Anyways, glad you found a fix.

– hb22
Nov 27 '18 at 19:56





@Thi hmm, I am unable to reproduce this error. Anyways, glad you found a fix.

– hb22
Nov 27 '18 at 19:56













@ht22 - yes, I see so many post here using List<String> but I can't. I am using eclipse, not sure that's the cause.

– Thi
Nov 29 '18 at 22:00





@ht22 - yes, I see so many post here using List<String> but I can't. I am using eclipse, not sure that's the cause.

– Thi
Nov 29 '18 at 22:00













@Thi List is higher in the collections hierarchy than ArrayList so make sure you are importing List instead of ArrayList. This way you can use either a List declaration or ArrayList. Be careful, though. Even if you declare a list you must instantiate it with something like an ArrayList.

– hb22
Feb 13 at 6:51





@Thi List is higher in the collections hierarchy than ArrayList so make sure you are importing List instead of ArrayList. This way you can use either a List declaration or ArrayList. Be careful, though. Even if you declare a list you must instantiate it with something like an ArrayList.

– hb22
Feb 13 at 6:51


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53463440%2fread-text-file-and-create-a-2d-array%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







這個網誌中的熱門文章

Academy of Television Arts & Sciences

L'Équipe

1995 France bombings