简体   繁体   English

Java“ 2D数组”问题

[英]Java “2D-array” issues

I have a table on a mySQL server that has data stored like this 我在mySQL服务器上有一个表,其中存储了这样的数据

Name Goal New Used Total Pace
Jill  5   6    1    7     0
Bob   5   2    3    5     0 
Ann   5   1    2    3     0

It can have many more than that in it. 它可以包含更多内容。 What I need to do is read in the data from the mySQL server and load it into a 2D String array. 我需要做的是从mySQL服务器读取数据并将其加载到2D String数组中。 I already know how to load sql data...the issue is I can not, for the life of me, figure out how to load it into the array. 我已经知道如何加载sql数据...问题是我一生无法解决如何将其加载到数组中的问题。

After the data is loaded into the array, it will be sent off to a table to be loaded for viewing. 数据加载到数组中后,将被发送到要加载的表中以供查看。

So basically the output of the array would need to be: 因此,基本上,数组的输出将需要为:

    Jill  5   6    1    7     0
    Bob   5   2    3    5     0 
    Ann   5   1    2    3     0

here is the code I have: 这是我的代码:

public String[][] fillInTableForStoreFromArchive(String Person, String DateTable) throws SQLException{

    stmt = con.createStatement(
            ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    rs = stmt.executeQuery("SELECT * FROM `" +DateTable+ "` WHERE name = '" +Person+"'"); 

    int rows = 0; //column number
    int columns = 6; //row number

    rows = getAmountOfSalesPeople(DateTable).length;
    String[][] data = new String[rows][columns]; 

    String name = null;
    int goal = 0, New = 0, used = 0,total = 0,pace = 0;
    while(rs.next()){

        name =  rs.getString("Name");
        goal = rs.getInt("Goal");
        New = rs.getInt("New");
        used = rs.getInt("Used");
        // total = rs.getInt("total");
        // pace = rs.getInt("pace");

        String[] mData = { name, new Integer(goal).toString(),
            new Integer(New).toString(), new Integer(used).toString(),
            new Integer(New + used).toString(),new Integer(pace).toString() };

        for(int row = 0; row >data.length; row ++){
            data[row] = mData;
        }
    }

    for(int row = 0; row < data.length; row++){
        for(int col = 0; col <data[row].length; col++){
            System.out.print(data[row][col] + " ");
        }
        System.out.println();
    }
    return data;
}

Looking at your example I'll make the assumption that name is unique. 在您的示例中,我将假设名称是唯一的。 Since you've got mixed types, Strings and ints, you can't put them all into one array unless you store the ints as Strings. 由于您混合使用了类型,字符串和整数,因此除非将整数存储为字符串,否则无法将它们全部放入一个数组中。 One solution would be to make an Object that holds a name and its associated data...that is, after all, something one does in object oriented programming. 一种解决方案是使一个对象拥有一个名称及其相关数据……毕竟,这是在面向对象编程中要做的事情。

Barring that I would store the data in a Map, where name is the key and an int array is the value: 除非我将数据存储在Map中,其中name是键,而int数组是值:

HashMap<String, int[]> myMap = new HashMap<String, int[]>();
String name;
int[] myData;
while(rs.next())
{
  myData = new int[5];
  name = rs.getString("Name");
  myData[0] = rs.getInt("Goal");
  myData[1] = rs.getInt("New");
  myData[2] = rs.getInt("Used");
  myData[3] = rs.getInt("total");
  myData[4] = rs.getInt("pace");
  myMap.put(name, myData);
}

It is then trivial to iterate over the map when needed (hint: use a Map.Entry<String, int[]> ), such as in toString() . 然后,在需要时遍历地图很简单(提示:使用Map.Entry<String, int[]> ),例如在toString() Arrays don't have "output" so you'll either need to use an object or a separate method to get the data formatted as needed. 数组没有“输出”,因此您将需要使用对象或单独的方法来获取所需格式的数据。

Also, avoid variable names like New...no good can come of names that are the same as keywords yet capitalized differently. 此外,请避免使用诸如New ...这样的变量名,与关键字相同但大小写不同的名称也无济于事。

Your problem is that youre trying to deal with array rows as independent entities, by setting a row ton other array... 您的问题是您试图通过设置其他数组的行来将数组行作为独立实体来处理...

... 2D arrays cannot be set at the "row" level - because they are not managed using row level pointers --- in order to set an 2D array row, you have to explicitly set and define the row and column 'for' each column in the row, in a proper "for" loop. ...无法在“行”级别设置2D数组-因为未使用行级指针管理它们-要设置2D数组行,您必须显式设置和定义行和列“ for”在适当的“ for”循环中,该行中的每一列。

Once you have the mdata array you want to use it as one of the rows in data . 一旦有了mdata数组,就想将其用作data中的行之一。 Instead you are using a cycle and assigning to several positions. 相反,您使用一个循环并分配给多个位置。

You should use a counter to keep track of how many rows have you added and then use that counter to put mdata in the right position. 您应该使用计数器来跟踪添加的行数,然后使用该计数器将mdata放在正确的位置。

As a corolary to @Paul's solution you can describe your table in a class and access it through normal OO principle. 作为@Paul解决方案的推论,您可以在一个类中描述您的表,并通过常规的OO原理进行访问。 That would completely eliminate the need for arrays. 那将完全消除对数组的需要。

Say for example : 例如说:

public class Player {

  private String name;
  private int goal;
  private int _new; //As @Paul pointed out you should not use reserved keywords
  private int used;
  private int total;
  private int pace;

  public Player(String name, int goal, int _new, int used, int total, int pace) {
        this.name = name;
        this.goal = goal;
        this._new = _new;
        this.used = used;
        this.total = total;
        this.pace = pace;
    }

    public String getName() {
        return name;
    }

    public int getGoal() {
        return goal;
    }

    public int get_new() {
        return _new;
    }

    public int getUsed() {
        return used;
    }

    public int getTotal() {
        return total;
    }

    public int getPace() {
        return pace;
    }
}

your initialization loop then becomes a much more readable : 您的初始化循环将变得更具可读性:

    List<Player> players = new ArrayList<Player>();
    while (rs.next()) {
        players.add(new Player(rs.getString("Name"), 
                                   rs.getInt("Goal"), 
                                   rs.getInt("New"), 
                                   rs.getInt("Used"), 
                                   rs.getInt("total"),  
                                   rs.getInt("pace")));
}

If you want to print information from your data good approach here would be to overload the toString of Player or to add a new method, say dumpToString(). 如果要从数据中打印信息,这里的好方法是重载Player的toString或添加一个新方法,例如dumpToString()。

public String dumpTostring() {
    StringBuilder sb = new StringBuilder();

    sb.append("Player ");
    sb.append(name);
    sb.append(" Goal=");
    sb.append(goal);
    sb.append(" New=");
    sb.append(_new);
    sb.append(" Used=");
    sb.append(used);
    sb.append(" Total=");
    sb.append(total);
    sb.append(" Pace=");
    sb.append(pace);

    return sb.toString();
}

and then just call in as part of a for each loop iterating through the list. 然后只需在循环遍历列表的每个循环中作为的一部分进行调用。

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

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