Ok this might seem easy but its been bugging my mind for days and I honestly don't know why it the index wont increase and get the other data. I dont know where to but the return. I placed it in 2 lines and the first one only gives the first row of data from the database and the second one only gives the last one from the database. (See commented out lines below). How to get each row that fits the if-statements?
Here's my code:
public Object[] populateTable(ArrayList<Outlet> outletList, String selection, int size, int monthCtr, String selDay){
for(int i = 0; i<outletList.size(); i++){
if(outletList.get(i).getCity().equalsIgnoreCase(selection)){
if(outletList.get(i).getStatus().equals("ACTIVE")){
bar = outletList.get(i).getBarangay();
code = Integer.toString(outletList.get(i).getCode());
name = outletList.get(i).getName();
data = new Object[]{bar, name, code};
//return data ->gives the first one in the database
}
}
}
}
//return data -> gives the last one in the database
}
You need to save all your results in another array and return that instead.
public Object[] populateTable(ArrayList<Outlet> outletList, String selection, int size, int monthCtr, String selDay)
{
List<object> result = new List<object>();
for(int i = 0; i<outletList.size(); i++)
{
if(outletList.get(i).getCity().equalsIgnoreCase(selection))
{
if(outletList.get(i).getStatus().equals("ACTIVE"))
{
bar = outletList.get(i).getBarangay();
code = Integer.toString(outletList.get(i).getCode());
name = outletList.get(i).getName();
data = new Object[]{bar, name, code};
result.Add(data);
}
}
}
return result.ToArray();
}
try this:
public List<Outlet> populateTable(ArrayList<Outlet> outletList, String selection, int size, int monthCtr, String selDay){
List<Outlet> data = new ArrayList<Outlet>();
for(int i = 0; i < outletList.size(); i++){
if(outletList.get(i).getCity().equalsIgnoreCase(selection) &&
outletList.get(i).getStatus().equals("ACTIVE")){
data.add(outletList.get(i));
}
}
return data;
}
Your problem here is as follow:
Your first return statement, will exit the for loop, and return
the first object, as your results have shown.
Your second return statement, will, as you have explained, only
return the last record that was iterated over in the for loop.
Your third problem is on this line data = new Object[]{bar, name,
code};. After every loop, you instantiate the data object to a new
array of objects, instead of adding the values to the array, so essentially, you are always creating an array of objects with 1 item in it, the last one that was iterated.
If you want to return all objects in the array, you should try the following:
public Object[] populateTable(ArrayList<Outlet> outletList, String selection, int size, int monthCtr, String selDay)
{
Object[] result = new Object[outletList.size()];
for (int i = 0; i < outletList.size(); i++)
{
if (outletList.get(i).getCity().equalsIgnoreCase(selection))
{
if (outletList.get(i).getStatus().equals("ACTIVE"))
{
bar = outletList.get(i).getBarangay();
code = Integer.toString(outletList.get(i).getCode());
name = outletList.get(i).getName();
var data = new { bar, name, code };
result[i] = data;
}
}
}
return result;
}
Related
public void setForm(mhs m)
{
String[] jurusan = {"TI","SI"};
JComboBox<String> cjurusan = new JComboBox<String> (jurusan);
String st;
st = ((String)m.getJurusan()).toUpperCase();
for(int i = 0; i < cjurusan.getItemCount(); i++)
{
String jur = ((String) cjurusan.getItemAt(i)).toUpperCase();
if(jur.equals("SI"))
{
cjurusan.setSelectedIndex(1);
}
else
{
cjurusan.setSelectedIndex(0);
}
}
tnim.setText(m.getNim());
tnama.setText(m.getNama());
cjurusan.setBounds(110,70,90,20);
add(cjurusan);
}
}
I want to set jcombobox's value according the data record in jtable, till now, I just get the data value at the first time, for second time the jcombobox's value is the same with last. please help. many thanks.
This is my sample image program : screenshoot
So I feel kind of stupid, because it looks like I'm missing something trivial and I've used loops before, but now we're at the stage in our class where we're using them a lot and I can't seem to find the problem after trying many different combinations, so here goes :
public class BusStop
{
private BusArrival[] _buses;
private int _noOfBuses;
final int MAX_ARRAY_SIZE = 1000;
//================================ CONSTRUCTORS ============================//
public BusStop(int size){ // THIS
_buses = new BusArrival[size]; // IS
// THE
for(int i=0; i< size; i++){ // PROBLEMATIC
if(_buses[i] != null){ // LOOP
_noOfBuses ++;
}
}
}
//=============================== METHODS =================================//
public int getNoOfBuses(){
return _noOfBuses;
}
public boolean add (int line, int pass, Time1 t){ // adds a BussArrival object to an empty array (if there's any).
for (int i=0; i < _buses.length; i++){
if(_buses[i] == null){
_buses[i] = new BusArrival(line, pass, t);
return true;
}
}
return false;
}
Here's a constructor of the BusArrival class, just so you have a general idea :
public BusArrival(int lineNum, int pass, Time1 t){
_lineNumber = lineNum;
_noOfPassengers = pass;
_arrivalTime = t;
}
And here's Time1 constructor from a saparate class, just for this to make sense :
public Time1(int h, int m, int s)
_hour = h;
_minute = m;
_second = s;
}
Here's my main method :
public class Test
{
public static void main (String [] args){
BusStop first = new BusStop(4);
Time1 one = new Time1(10,30,0);
Time1 two = new Time1(10,0,0);
first.add(1,2,one);
first.add(2,3,two);
System.out.println(first.getNoOfBuses());
}
}
Unfortunately the output is "0" when I do that.
Any help would be appreciated.
Thanks.
Here's the problem.
Number of buses is only assigned in the initializer, but in the initializer you aren't adding any buses. Hence you get 0 buses.
When you add a bus, you are not updating number of buses. So you get 0.
You should do _noOfBuses++; when you successfully added a bus. Also, take out that loop in the initializer. When you initialized an array all the entries are null, so the loop is useless :)
Edit:
You seem to be confused about the order of execution of your code.
In your main function, you are first initializing a BusStop. This means he initializer code is ran (which includes the loop in your initializer).
Then you added the two buses. However, note that the loop is already executed, it won't be executed again, because the initializer is only run once.
Therefore, your loop is never going to increment _noOfBuses
You need to increase the number of busses every time that you add a new one.
public BusStop(int size){ // THIS
_buses = new BusArrival[size]; // IS
// THE
for(int i=0; i< size; i++){ // PROBLEMATIC
if(_buses[i] != null){ // LOOP
_noOfBuses ++;
}
}
}
In the above code the array _buses just gets created with all the items pointing to null. In your for-loop you are using if statement to check if there is any non-null value (which in this case does not exist because there are no items in the array). so your _noOfBuses ++; is not reachable.
First Add another constructor with no arguments to your BusArrival class. Just like this.
public BusArrival() {}
Second Modify the BusStop constructor to the following
public BusStop(int size){
_buses = new BusArrival[size];
for(int i=0; i<_buses.length; i++) {
_buses[i] = new BusArrival();
_noOfBuses ++;
}
}
As written in the title, I check my SQL database with following method:
public String[] getRecord(String category){
String[] record = new String[3];
Cursor crsRecord = sqliteDatabase.rawQuery(QUERY_GET_RECORD + category, null);
int i=0;
while(crsRecord.moveToNext()){
record[i] = crsRecord.getString(0);
i++;
}
return record;
}
Now it could be that the line:
Cursor crsRecord = sqliteDatabase.rawQuery(QUERY_GET_RECORD + category, null);
has no result, because I have no appropriate data in my database. How can I check that I have no result?
cursor.moveToFirst();
if (cursor.isAfterLast()){
// You have no results
}
Or, you could just change your code to this:
while(!crsRecord.isAfterLast()){
// Instead of using an int literal to get the colum index,
// use the getColumnIndex method
int index = crsRecord.getColumnIndex(COLUMN_NAME);
if (index == -1) {
// You don't have the column-- do whatever you need to do.
}
else {
record[i] = crsRecord.getString(index);
i++;
}
crsRecord.moveToNext();
}
If there are no records, the while loop never starts.
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.
Can someone could be kind and help me out here. Thanks in advance...
My code below outputs the string as duplicates. I don't want to use Sets or ArrayList. I am using java.util.Random. I am trying to write a code that checks if string has already been randomly outputted and if it does, then it won't display. Where I am going wrong and how do I fix this.
public class Worldcountries
{
private static Random nums = new Random();
private static String[] countries =
{
"America", "Candada", "Chile", "Argentina"
};
public static int Dice()
{
return (generator.nums.nextInt(6) + 1);
}
public String randomCounties()
{
String aTemp = " ";
int numOfTimes = Dice();
int dup = 0;
for(int i=0 ; i<numOfTimes; i++)
{
// I think it's in the if statement where I am going wrong.
if (!countries[i].equals(countries[i]))
{
i = i + 1;
}
else
{
dup--;
}
// and maybe here
aTemp = aTemp + countries[nums.nextInt(countries.length)];
aTemp = aTemp + ",";
}
return aTemp;
}
}
So the output I am getting (randomly) is, "America, America, Chile" when it should be "America, Chile".
When do you expect this to be false?
countries[i].equals(countries[i])
Edit:
Here's a skeleton solution. I'll leave filling in the helper methods to you.
public String[] countries;
public boolean contains(String[] arr, String value) {
//return true if value is already in arr, false otherwise
}
public String chooseRandomCountry() {
//chooses a random country from countries
}
//...
int diceRoll = rollDice();
String[] selection = new String[diceRoll];
for ( int i = 0; i < selection.length; i++ ) {
while (true) {
String randomCountry = chooseRandomCountry();
if ( !contains(selection, randomCountry ) {
selection[i] = randomCountry;
break;
}
}
}
//...then build the string here
This doesn't check important things like the number of unique countries.
You need a data structure which allows you to answer the question "does it already contain item X?"
Try the collection API, for example. In your case, a good candidate is either HashSet() or LinkedHashSet() (the latter preserves the insert order).
You'd probably be better of using another structure where you save the strings you have printed. Since you don't want to use a set you could use an array instead. Something like
/*
...
*/
bool[] printed = new bool[countries.length];
for(int i=0 ; i<numOfTimes ; /*noop*/ )
{
int r = nums.nextInt(countries.length);
if (printed[r] == false)
{
i = i + 1;
printed[r] = true;
aTemp = aTemp + countries[r];
aTemp = aTemp + ",";
}
}
return aTemp;
Consider what you're comparing it to:
if (!countries[i].equals(countries[i]))
are you comparing c[i] to c[i]? or c[i] to c[i-1]? Or do you need to check the whole array for a particular string? Perhaps you need a list of countries that get output.
make list uniqueCountries
for each string called country in countries
if country is not in uniqueCountries
add country to uniqueCountries
print each country in uniqueCountries
When you do this, watch out for index out of bounds, and adjust accordingly
Much faster way to do it then using HashSets and other creepy stuff. Takes less code too:
public String randomCounties() {
List<String> results = Arrays.asList(countries);
Collections.shuffle(results);
int numOfTimes = Dice();
String result = " ";
for(int i=0 ; i<numOfTimes; i++) {
result = result + countries[i] + ", ";
}
return result;
}
If you want to avoid outputting duplicate values, you need to record what values have already been listed or remove values from the pool of possibilities when they get selected.
You mention that you do not want to use Sets or ArrayList (I assume you mean Lists in general), I assume that is a requirement of the assignment. If so, you can accomplish this by building arrays and copying data between them the same way that an ArrayList would.
one note, your current implementation chooses between 1 and 6 entries from and array of 4 entries. If you force the selections to be unique you need to decide how to handle the case when you have no more unique selections.