【问题标题】:Converting numbers in a string array to a two dimensional int array将字符串数组中的数字转换为二维 int 数组
【发布时间】:2023-03-19 02:16:01
【问题描述】:

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

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[][],以便我可以按列和行操作数字?感谢您的宝贵时间。

【问题讨论】:

  • 您可以使用 OOP 并为每一行创建一个 Student 对象。这将导致更好的可读性设计。

标签: java arrays string multidimensional-array type-conversion


【解决方案1】:

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

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]);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-28
    • 1970-01-01
    • 2021-01-28
    相关资源
    最近更新 更多