I need to take a text file like the one below and create a 2d array from the numbers in it. However, it needs to be very general so that it could apply to a text file with more or fewer entries than this one.
1 1 11
1 2 32
1 4 23
2 2 24
2 5 45
3 1 16
3 2 37
3 3 50
3 4 79
3 5 68
4 4 33
4 5 67
1 1 75
1 4 65
2 1 26
2 3 89
2 5 74
This is what I have so far, but it just gives me all zeroes when I print it.
import java.util.*;
public class MySales11 {
//variables
private ArrayList<String> list = new ArrayList<>();
private int numberOfEntries;
private int [][] allSales;
//constructor
public MySales11 (Scanner scan) {
//scan and find # of entries
while (scan.hasNext()){
String line = scan.nextLine();
list.add(line);
}
//define size of AllSales array
allSales = new int[list.size()][3];
//populate AllSales array with list ArrayList
for(int a = 0; a < allSales.length; a++){
String[] tokens = list.get(a).split(" ");
for(int b = 0; b < tokens.length; b++){
allSales[a][b] = Integer.parseInt(tokens[b]);
}
}
}
}
You read all the lines when you wanted to create a array of size numOfEntries.
while (scan.hasNext()) {
scan.nextLine();
numberOfEntries++;//this reads all the lines but never stores
}
allSales = new int[numberOfEntries][3];
while (scan.hasNext()) {//input is empty
//the execution never comes here.
}
Now the input is empty. So it'll never add values to the array.
You can use an arrayList
, dynamic - no need to calculate number of lines.
ArrayList<String> list = new ArrayList();
while (scan.hasNext()) {
String s = scan.nextLine();
list.add(s);
}
int [][] myArray = new int[list.size()][3];
for(int i = 0; i < myArray.length; ++i)
{
String[] tokens = list.get(i).split("\\s+");//extra spaces
for(int j = 0; j < tokens.length; ++j)
{
myArray[i][j] = Integer.parseInt(tokens[j]);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.