[英]Reading a text file with Scanner and turning it into a 2d int array
[英]Turning text file into a 2d array
我需要一個像下面的文本文件,並根據其中的數字創建一個二維數組。 但是,它必須非常籠統,以便它可以應用於條目比該條目更多或更少的文本文件。
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
到目前為止,這就是我所擁有的,但是在我打印時,它只會給我所有零。
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]);
}
}
}
}
當您要創建一個大小為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.
}
現在輸入為空。 因此,它永遠不會向數組添加值。
您可以使用動態的arrayList
-無需計算行數。
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]);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.