如何使用二维数组存储数据

时间:2016-04-21 03:10:56

标签: java arrays dictionary

.txt文件。如何使用java来读取文件并使用二维数组(用户的一个维度和产品的其他维度)来存储订单#?另外,如何使用字典将每个用户映射到相应的数组行?如何在2D数组中用0替换缺失值?

用户,产品,订单#:

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  

//下面是我的try-catch块尝试读取文件并生成2d数组

try{            
        File file = new File("src/users.txt");
        FileReader fr = new FileReader(file);
        BufferedReader br = new BufferedReader(fr);
        Scanner userScanner = new Scanner(br);

        List<Order> orders = new ArrayList<>(); //Order class for store the order information
        while (userScanner.hasNextLine()){
            String line = userScanner.nextLine();
            String[] columns = line.split("\\t");

            String userId = columns[0];
            String productId = columns[1];  
            int order = Integer.parseInt(columns[2]);

            Order order = new Order(userId, productId, order); //construct order
            orders.add(order);


        }

        int[][] matrix = new int[orders.size()][];
        for (int i = 0; i < orders.size(); i++){
            //how to put the data into 2d array?
        }


    }catch (Exception e){
        e.getMessage();
    }

1 个答案:

答案 0 :(得分:0)

我想你想要关注输出:

名称[行] V产品[col]

5 0 2
3 1 0
5 0 2
3 1 0

目录:{name3 = 2,name4 = 3,name1 = 0,name2 = 1}

检查以下解决方案:

    Map<String, LinkedHashMap<String, Integer>> 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<String, Integer> prodMap = orderInfo.get(userId);
        if (prodMap == null || prodMap.isEmpty()) {
            prodMap = new LinkedHashMap<String, Integer>();
        }
        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<String,Integer> dictionary = new HashMap<String,Integer>();

    for (Entry<String, LinkedHashMap<String, Integer>> entry : orderInfo.entrySet())
    {
        dictionary.put(entry.getKey(), row);
        matrix[row] = new int[entry.getValue().size()];
        int columns = 0;
        for(Entry<String, Integer> 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);