【问题标题】:How to convert a 2d array in String to int?如何将String中的二维数组转换为int?
【发布时间】:2012-01-13 04:24:16
【问题描述】:

我的程序是将一个 txt 文件输入到一个二维数组中,用于计算和呈现一些数据。

我的输入文件如下所示:

[学生],考试1,考试2,考试3

五月, 100, 100, 100

彼得, 99, 60, 80

约翰, 100, 50, 100

我是 Java 新手。将 txt 文件输入二维数组后,数组将是 String 数据类型,如何将其转换为 int 类型,以便我可以计算一些统计数据,例如每个学生的平均分、总分或班级平均分?并且应该把计算?

我的代码:

    File file = new File("test.txt");
    BufferedReader br = new BufferedReader(new FileReader(file));
    int width = 0, height = 0;
    String line = "";

    /*Find number of row and column of the file.*/
    while ((line = br.readLine()) != null){
      if (width == 0){
                  /*Find the number of row using split method(",")*/
                    String[] str = line.split(",");
                    width = str.length;
      }
      height++;
    }
    System.out.println("The text file contains:");
    System.out.println("Row : " + height);
    System.out.println("Column : " + width);
    System.out.println("");
    System.out.println("The sales figure of the company:");

    /*Adding values to the 2D Array and organize data.*/
    String[][] data = new String[height][width];
    br = new BufferedReader(new FileReader(file));
    int columnWidth = 20;
    StringBuilder format;
    int addition = 0;

    for (int i = 0; i < height; i++){
        if ((line = br.readLine()) != null)
        {
          String[] str = line.split(",");

          for (int j = 0; j < width; j++){
            data[i][j] = str[j];
            format = new StringBuilder(str[j]);

            for (int k = format.length(); k< columnWidth; k++){
              format.append(" ");
            }
            System.out.print(format.toString());
          }
        }
        System.out.println("");
    }
    System.out.println();
}

谢谢大家=]

【问题讨论】:

  • Integer.parseInt(String s) - 这会将您的 String 转换为 int
  • 我添加了homework 标签,因为这显然功课
  • 将数组中的所有String转换为int的语句应该放在哪里?
  • 这就是发明fizzbuzz的原因!

标签: java string multidimensional-array


【解决方案1】:

请使用 Integer.parseInt(String value) 将字符串转换为整数

【讨论】:

  • 这句话应该在哪里?我应该使用 for 循环吗?
  • @Benson:现在您有一个清晰的示例,将每个值分配给二维字符串数组 (data)。将data 声明为int[][],当您将值分配给数组中的某个位置时,请在该点使用parseInt
  • 对不起,还是不明白。单独扫描文件时,是字符串,如何以及在哪里可以将其转换为int?
  • @Benson:你自己努力吧,我们不是来帮你做功课的。查看data[i][j] = str[j] 行,想象一下如果dataint[][] 而不是String[][],那会发生什么变化。如果您不明白如何将单个 String 转换为单个 int,请解释一下您对 hakish 的中肯回答的不理解之处。
猜你喜欢
  • 2015-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-28
  • 1970-01-01
相关资源
最近更新 更多