java - 将字符串数组中的数字转换为二维 int 数组

标签 java arrays string multidimensional-array type-conversion

我正在从包含以下信息的文本文件中获取数据:

Jessica 80 90
Peter 106 50
Lucas 20 85
Sarah 90 40
John 35 12

然后,该数据将被转换为字符串数组并由我的代码输出。我希望能够将名称保留在字符串数组中,同时将数字转换为 int[][] 数组,以便我可以操纵变量来查找学生和考试的平均值。我的工作代码如下:

import java.io.*;
import java.util.*;

public class Array_2D{

public static String[] readLines(String filename) throws IOException {
        FileReader fileReader = new FileReader(filename);

        BufferedReader bufferedReader = new BufferedReader(fileReader);
        List<String> lines = new ArrayList<String>();
        String line = null;

        while ((line = bufferedReader.readLine()) != null) {
            lines.add(line);
        }

        bufferedReader.close();

        return lines.toArray(new String[lines.size()]);
}   

public static void inputstream() throws IOException {
       String filename = "data.txt";
       try {
           String[] lines = readLines(filename);
           for (String line : lines)
           {
               System.out.println(line);
           }
       } catch(IOException e) {
           System.out.println("Unable to create " + filename+ ": " + e.getMessage());
       }

有谁有任何信息可以帮助我将数字从字符串数组转换为int[][],以便我可以按列和行操作数字?感谢您抽出时间。

最佳答案

在您的代码中,每一行包含一个名称和两个整数, 这可能不是通用的,但尝试类似的东西,

String names = new String[numberOfLines];
int scores[][] = new int[numberofLines][2];
for(int i = 0;i < numberOfLines;i ++){
  String words[] = lines[i].split("\\s+");
  names[i] = words[0];
  scores[i][0] = Integer.parseInt(words[1]);
  scores[i][1] = Integer.parseInt(words[2]);
}

关于java - 将字符串数组中的数字转换为二维 int 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46433151/

相关文章:

c++ - 程序总是产生相同的值(value)?

java - 从 JSONObject 获取 Vector 对象

c - 在C中将字符串添加到char数组

r - 使用 R 中的 data.table 将一列字符串拆分为可变数量的列

arrays - 根据 MA​​TLAB 中另一个矩阵中的索引从矩阵中选择条目

c - 在如何修改单个特定函数调用时遇到问题

javascript - 过滤 js 中长度小于 < 50 个字符的内容

全局变量的java单独文件

java - 类中私有(private)构造函数的使用

java - roguelike 游戏的纯 Java 文本界面