h******o 发帖数: 334 | 1 A .txt file. Use the below java code to read the file and use a 2-D array (
one dimension for the users and other dimension for the products) to store
the order#. Also, use a dictionary to map each users to its corresponding
array row. How to replace the missing value with 0 in the 2D array?
Users, Products, order#:
name1 p1 5
name1 p2
name1 p3 2
name2 p1 3
name2 p2 1
name2 p3
name3 p1 5
name3 p2
name3 p3 2
name4 p1 3
name4 p2 1
name4 p3
output:
5 0 2
3 1 0
5 0 2
3 1 0
请问一下,怎样把missing value替换成0 放在新生成的2D array里面?
多谢!下面是我已经有的code,
我的code只能产生:
5 2
3 1
5 2
3 1
Map> orderInfo = new LinkedHashMap<>(
);
while (userScanner.hasNextLine()) {
String line = userScanner.nextLine();
// To-Do : check regx
String[] columns = line.split("\t");
String userId = columns[0];
String productId = columns[1];
int order = Integer.parseInt(columns[2]);
LinkedHashMap prodMap = orderInfo.get(userId);
if (prodMap == null || prodMap.isEmpty()) {
prodMap = new LinkedHashMap();
}
prodMap.put(productId, new Integer(order));
orderInfo.put(userId, prodMap);
}
int[][] matrix = new int[orderInfo.size()][];
int row = 0 ;
// dictionary will contain Name as a key and belonging row as a value
Map dictionary = new HashMap();
for (Entry> entry : orderInfo.
entrySet())
{
dictionary.put(entry.getKey(), row);
matrix[row] = new int[entry.getValue().size()];
int columns = 0;
for(Entry ent : entry.getValue().entrySet())
{
matrix[row][columns] = ent.getValue();
columns = columns + 1;
}
row = row + 1;
}
for (int rw = 0; rw < matrix.length; rw++) {
for (int col = 0; col < matrix[rw].length; col++) {
System.out.print(matrix[rw][col]+" ");
}
System.out.println();
}
System.out.println(dictionary); |
z*y 发帖数: 1311 | 2 I wonder why your code can still run.
Shouldn't it raise NumberFormatException when parseInt fails? |
h******o 发帖数: 334 | 3 如果把missing value 用0替换后,就可以运行。我现在不知道怎么把missing value替
换成0当从文件中读取data。
【在 z*y 的大作中提到】 : I wonder why your code can still run. : Shouldn't it raise NumberFormatException when parseInt fails?
|
z*y 发帖数: 1311 | 4
you can either sanity check the value before parseInt, or
int order;
try {
order = Integer.parseInt(columns[2]);
}
catch (NumberFormatException e) {
order = 0;
}
【在 h******o 的大作中提到】 : 如果把missing value 用0替换后,就可以运行。我现在不知道怎么把missing value替 : 换成0当从文件中读取data。
|
h******o 发帖数: 334 | 5 多谢!
【在 z*y 的大作中提到】 : : you can either sanity check the value before parseInt, or : int order; : try { : order = Integer.parseInt(columns[2]); : } : catch (NumberFormatException e) { : order = 0; : }
|