简体   繁体   中英

Java “2D-array” issues

I have a table on a mySQL server that has data stored like this

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. 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.

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:

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() . 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.

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.

Once you have the mdata array you want to use it as one of the rows in 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.

As a corolary to @Paul's solution you can describe your table in a class and access it through normal OO principle. 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().

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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