所以我需要从用户的标准输入中读取一个整数矩阵。矩阵将在列之间用空格指定,每行在新行上。输入以-1结束。
输入
3 9 7 1
2 4 8 6
3 7 9 2
-1
我知道2D阵列不能使用,因为矩阵的维度是未知的。我读过关于2d数组列表的文章,但我不确定如何存储或读取用户的信息。
感谢提供的任何帮助
您可以创建integers
的ArrayList
的ArrayList
例如:
ArrayList<ArrayList<Integer>> matrix = new ArrayList<>();
示例代码:
ArrayList<ArrayList<Integer>> matrix = new ArrayList<>();
private void buildMatrix() {
String rows [] = new String[10];
for(String eachRow: rows) {
matrix.add(processRow(eachRow));
}
}
public ArrayList<Integer> processRow(String row) {
ArrayList<Integer> rowInts = new ArrayList<>();
if (null != row && row.contains(" ")) {
String numbers[] = row.split(" ");
for (String number : numbers) {
try {
int numberAsInt = Integer.parseInt(number);
rowInts.add(numberAsInt);
} catch (NumberFormatException ex) {
ex.printStackTrace();
}
}
}
return rowInts;
}
手动重复输入数据似乎是一种真正的拖动。可能需要从文件中读取。
/**
* Load a set of loot items into loot table from a CSV file
* @param fileName expected CSV format: | String name | int tries |
* @throws NumberFormatException if 2nd column isn't an integer
* @throws FileNotFoundException if can't find the CSV file
* @throws IOException other I/O & storage problems
*/
public void load(String fileName){
try {
BufferedReader fileReader = new BufferedReader(new FileReader(fileName));
String lineItem;
while ((lineItem = fileReader.readLine()) != null) {
String[] lootDetails = lineItem.split(",");
lootRecord record = new lootRecord();
record.name = lootDetails[0];
record.tries = Integer.valueOf(lootDetails[1]);
table.add(record);
}
fileReader.close();
}
catch (NumberFormatException e) {
System.out.println("Invalid String: Integer count of tries expected");
e.printStackTrace();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
} // load