简体   繁体   English

在2D数组中存储字符串和整数

[英]storing a string and int in 2d array

Hello i am trying to understand 2d arrays in java. 您好,我试图了解Java中的2D数组。 Basically i am trying to take cellular data from each country and display it like this: 基本上,我试图从每个国家/地区获取蜂窝数据并像这样显示:

Country 1983 1984 1985 USA 10 20 40 Mexico 2 3 1 国家1983 1984 1985美国10 20 40墨西哥2 3 1

Basically taking a string representing country and int representing actual stat number. 基本上采用代表国家的字符串和代表实际统计数字的整数。 i take the stats from 1983 to 1985. 我采用1983年至1985年的统计数据。

My assumption not sure if i am right: Create an object of 2d array. 我的假设不确定我是否正确:创建2d数组的对象。 1 for string, 2nd for int. 1用于字符串,第二用于int。 but get lost on the implementation and don't know if this is the right way to go or if anyone could help and make any suggestion will be grateful. 但会迷失在实现上,并且不知道这是否是正确的方法,或者是否有人可以帮助并提出任何建议将不胜感激。

Any suggestion will be helpful. 任何建议都会有所帮助。

below is my sample code implementation: 以下是我的示例代码实现:

public class CellularData
 {
   private String []country;
   private double []stats;
   CellularData [][]array;
   private int year;

  public CellularData(int rows, int column, int year){
  this.country = new String[rows];
  this.stats = new double[column];
  array = new CellularData[country.length][stats.length];
  this.year = year;
   }
  public void insert(String country, double []num){
   //this is where I'm having the problem.
  //don't think  i am right.
     for(int i=0;i<array.length;i++)
        {
             array[i] = country;
          for(int j =0;j<array[i].length;j++)
            {
              array[i][j] = num[j];
            }
         }
   }




  //Below is my Test class
  public class TestCellularData(){
  public static void main(String []args){
   final double[] canada = {0,0,0.05,0.23,0.37,0.75,1.26};
              final double[] mexico = {0,0,0,0,0,0,0.01};
              final double[] usa = {0,0,0.14,0.28,0.5,0.83,1.39};
              int startingYear = 1983;
              CellularData datatable;
              int numRows = 3;
              int numColumns = canada.length;
              datatable = new CellularData(numRows, numColumns, startingYear);
              datatable.insert("canada", canadaPartial);
              datatable.insert("mexico", mexicoPartial);
              datatable.insert("usa", usaPartial);

              System.out.println(datatable);

Your provided source code has some small problems in it. 您提供的源代码中有一些小问题。 First of all, you'll have to use an array of Object to store String and Double in it. 首先,您必须使用Object数组在其中存储StringDouble An array of CellularData can't do that. CellularData数组无法做到这一点。

The second problems was your insert method. 第二个问题是您的insert方法。 It wrote data to every row of the array and delete already stored data that way. 它将数据写入数组的每一行,并以此方式删除已存储的数据。 To fix that you'll have to search for the first empty row first. 要解决此问题,您必须先搜索第一个空行。

See the following code and the comments for more information. 有关更多信息,请参见以下代码和注释。

public class CellularData {
  private Object[][] array; // <- use Object instead of CellularData

  public CellularData(int rows, int column, int year) {
    array = new Object[rows + 1][column + 1]; // <- +1 for the heading line and the country name column

    // write head line to array
    array[0][0] = "Country";
    for (int i = 1; i <= column; i++) {
      array[0][i] = year++;
    }
  }

  public void insert(String country, double[] num) {
    for (int i = 0; i < array.length; i++) {
      if (array[i][0] == null) { // <- search for an empty row to insert the data there
        insert(country, num, i);
        break;
      }
    }
  }

  private void insert(String country, double[] num, int row) {
    array[row][0] = country; // <- write the country to the first column
    for (int j = 1; j < array[row].length; j++) { // <- data starts at the second column
      array[row][j] = num[j - 1]; // <- -1 because the num array is one column shorter than 'array' (due to the country name column in 'array')
    }
  }

  public static void main(String[] args) {
    final double[] canada = { 0, 0, 0.05, 0.23, 0.37, 0.75, 1.26 };
    final double[] mexico = { 0, 0, 0,    0,    0,    0,    0.01 };
    final double[] usa =    { 0, 0, 0.14, 0.28, 0.5,  0.83, 1.39 };
    int startingYear = 1983;
    CellularData datatable;
    int numRows = 3;
    int numColumns = canada.length;
    datatable = new CellularData(numRows, numColumns, startingYear);
    datatable.insert("canada", canada);
    datatable.insert("mexico", mexico);
    datatable.insert("usa", usa);

    // print array content
    for (Object[] row : datatable.array) {
      for (Object cell : row) {
        System.out.print(cell + "\t");
      }
      System.out.println();
    }
  }
}

The test method prints 测试方法打印

Country 1983    1984    1985    1986    1987    1988    1989    
canada  0.0     0.0     0.05    0.23    0.37    0.75    1.26    
mexico  0.0     0.0     0.0     0.0     0.0     0.0     0.01    
usa     0.0     0.0     0.14    0.28    0.5     0.83    1.39    

You could instead create an object that encapsulates these data points, and store that in a one-dimensional array instead. 相反,您可以创建一个封装这些数据点的对象,并将其存储在一维数组中。 You could even make them sortable by the year by implementing Comparable . 您甚至可以通过实施Comparable使它们按年份排序。

public class CountryData implements Comparable<CountryData> {
    private final Integer year;
    private final String country;
    private final Integer dataPoint;

    public CountryData(Integer year, String country, Integer dataPoint) {
        this.year = year;
        this.country = country;
        this.dataPoint = dataPoint;
    }

    // presume getters defined

    public int compareTo(CountryData other) {
        return year.compareTo(other.getYear());
    }
}

Alternatively, if you're feeling particularly adventurous, you could experiment with Guava's Table as well. 另外,如果您特别喜欢冒险,也可以尝试使用番石榴

Table<Integer, String, Integer> countryData = HashBasedTable.create();
countryData.put(1983, "USA", 10);
// and so forth

you can use an array of Object class like 您可以使用Object类的数组

Object[][] ob = {{"One", 1},{"Two", 2}, {"Three", 3}};

Note: to access the values you will need to cast the values to the required type (string does not need to be cast explicitly) 注意:要访问值,您需要将值转换为所需的类型(不需要显式转换字符串)

OR 要么

you should use HashMap Like 你应该使用HashMap Like

HashMap<String, Integer> map = new HashMap<>();

use its put(String, Integer) method to insert the values and get(index) to access the values 使用其put(String, Integer)方法插入值,并使用get(index)访问值

Note: You cannot store the primative types in a HashMap but you will have to use Integer instead of int and later you can change it to int. 注意:您不能将基本类型存储在HashMap但是必须使用Integer而不是int,以后可以将其更改为int。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM