Printing arraylist elements in textfield - java

Actually I want to show the first element of arraylist in textfield1 and its next element in textfield 2 I want it to keep rotating whenever I press button. The problem is that it keeps showing the last element in both textfields
public class Teams
{
String[] P={"Hi","there","you"};
}
Teams tm=new Teams();
for(int j=0;j<=tm.P.length; j++){
textfield1.setText(tm.P[j]);
textfield2.setText(tm.P[j+1]);
}

You can perform an additional check (If-Else).
if textfield1's text is equals to the array[1] then
do swapping.
If it will be there. It will swap it. If not then that If check will be ignored.
This is the answer what I understood your question so far.

You should get the ArrayIndexOutOfBoundsException exception when you run this code. Your code will terminate with the exception.
According to your example tm.P.length is 3.
When j=2,
textfield1= there
textfield2= you
when j=3,
textfield1= you
and
textfield2.setText(tm.P[j+1]);
is getting the exception (ArrayIndexOutOfBoundsException)and terminate the flow since tm.P[4] (there is no such a location in the array)but textfield2 previous value is "you"
So your final result is
textfield1= you
textfield2= you

From what I get from your code :
public class Teams{
String[] P={"Hi","there","you"};
}
Another class
//Inside some function in another class
Teams tm=new Teams();
for(int j=0;j<=tm.P.length; j++){
textfield1.setText(tm.P[j]);
textfield2.setText(tm.P[j+1]);
}
The variable P in class Teams has length 3. So in the code snippet below the value of j changes from 0 to 3. In the case when the value of j is 2 the line
textfield2.setText(tm.P[j+1]);
should throw ArrayIndexOutOfBoundsException as the index j+1 i.e. 3 does not exist for P.
Also when the value of P is 3 both the lines
textfield1.setText(tm.P[j]);
textfield2.setText(tm.P[j+1]);
should throw an ArrayIndexOutOfBoundsException as the index of P is 3 for the first line and 4 for the second line.
Now since you have stated clearly in your comments that there is not exception being thrown, I feel that this code must be inside a try - catch block which catches Exception objects. Also this should explain why this kind of behaviour of show the last value of P in both text fields happen.
When j is 1, textfield2.setText(tm.P[j+1]) the text to this field is set to the last element "you". Now in the next loop when j attains the value 2 the first text field textfield2 gets set to the last element "you". But in the next line an exception is thrown so the line is not executed so the text of textfield2 remains to you.
finally when j is 3 the first line itself throws the exception so that the code after the first line is not executed and both textfield1 and textfield2 have text values "you" stored in them and that is what is displayed and results to the problem you have highlighted.

Related

Java - Index Out Of Bounds Exception: Index: 1, Size: 2

While working on some java project I encountered this peculiar error:
java.lang.IndexOutOfBoundsException: Index: 1, Size: 2
How can there be an index out of bounds exception? Index 1 means it tries to get the second element, Size 2 means there are 2 elements, so there shouldn't be a problem, no?
Context:
I have the following function:
public int howManyAgents(){
// cell is a class that can have 0 or multiple objects
// I get a list of cells that contain at least 1 agent
List<Cell> cellsWithAgents = getNonEmptyCells();
// initializing a counter
int agentsCount = 0;
for(int i=0; i<cellsWithAgents.size(); i++){
// For every cell in the list I add to the counter the number of
// agents that cell contains
agentsCount += cellsWithAgents.get(i).howManyAgents();
}
return agentsCount;
}
Now, the problem was that I got a null pointer exception at the line:
agentsCount += cellsWithAgents.get(i).howManyAgents();
I want to debug the code, but this function is called many times while the program is running and the null pointer exceptions comes up at different points in time (after 10 seconds after 1 minute after 5 minutes). So I tried to come up with a method to have e breakpoint when the cell is null so I came up with this code:
public int howManyAgents(){
// cell is a class that can have 0 or multiple objects
// I get a list of cells that contain at least 1 agent
List<Cell> cellsWithAgents = getNonEmptyCells();
// initializing a counter
int agentsCount = 0;
for(int i=0; i<cellsWithAgents.size(); i++){
int pass;
if (null == cellsWithAgents.get(i))
pass = 1; // breakpoint here
// For every cell in the list I add to the counter the number of
// agents that cell contains
agentsCount += cellsWithAgents.get(i).howManyAgents();
}
return agentsCount;
}
Of course, it is not the best method. The most logical way is jut to surround the code with try/catch and put the breakpoint there. The point is that the code above didn't work. It did not stop at the breakpoint but instead it threw the index out of bounds exceptions at the line:
if (null == cellsWithAgents.get(i))
Why? How can it be possible to throw an index out of bound exception if apparently the index is in bounds?
Edit: changed a mistake in copying the code
Update:
I have tried to see why the null pointer exception appears with a try/catch and put a breakpoint there. It seems that cellsWithAgents sometimes contains a null. This is, most probably because of concurrency as #rlinden stated.
About concurrency: there are some cells that can contain agents. There is a variable number of agents that can move between the cells. There is a special agent that tries to count how many moving agents there are (using this function).
So, only one agent (thread) can use this function, but multiple agents can modify cells (and thus mess with getNonEmptyCells() and howManyAgents() results).
Still, how it is possible to get index out of bounds with size 2 and index 1? It is not possible because of the concurrency, is it? Because only this thread can change the list cellsWithAgents. So, even if one of the elements in the list becomes null, the list still contains that number of pointers, so the size of the list cannot change. Or can it in some way that I miss?
And how can it be explained that the stack trace prints Index:1 Size: 2?
New Idea
Try changing the loop and see if the error persists:
int agentsCount = 0;
for(Cell cell : getNonEmptyCells()) {
if(cell != null) {
agentsCount += cell.howManyAgents();
} else {
System.out.println("Found a null cell");
}
}
I would like to see the code of the method getNonEmptyCells(). If your program is actually multithreaded and this function returns a fixed List that is changed at every interaction, then it is possible that changes in following executions have affected the previous, unfinished ones.
This is due to the fact that the line cellsWithAgents = getNonEmptyCells(); does not create a copy, but a reference to the return value of getNonEmptyCells(). So, if this method reuses the return object, it is possible that the first execution would believe there was two, but the concomitant thread changed the content size to less than 2.
The problem is, program is throwing exception at cellsWithType.get(i). What you can do is either put a breakpoint at if (null == cellsWithType.get(i)) and try debug it. Or change it to,
if (i >= cellsWithType.size())
pass = 1; // breakpoint here

Objects field changes for unknown reason

I am writing a program dealing with subnets.
In simpleIPaddress.class line 315, the object Ted's fullSubnetAddress = "111.111.111.111".
In simpleIPaddress.class line 317, the object Ted's fullSubnetAddress changes for some reason I can not figure out. It changes to the as textAddress the field variable for the class. textAddress is generated from the program earlier in the code when the simpleIPaddress address is initially created from user input.
After the first time the for loop is executed, Ted is changed permanently for the rest of the for loop.
In the code I am slowly populating an array.
SubnetItem ted = new SubnetItem(subnetNumber, fullSubnetAddress, fullStartHost,
fullEndHost, fullBroadcastAddress);
this.subnetArray = new SubnetItem[totalSubnets];
for (int i = 0; i < subnetArray.length; i++)
{
this.subnetArray[i] = ted; // line 315
this.subnetArray[i].setSubnetNumber(i);
System.out.println(ted.toString()); // line 317
calculateStartingAddress(i);
System.out.println(ted.toString());
System.out.println(subnetArray[i].toString());
}
Here is the full code if that is needed.
You create only one SubnetItem object, then inside the for loop you repeatedly modify that single object while assigning every element of the array to point at the object. By the time the loop is over, you have an array full of pointers to the same object, now having the last value assigned to it.
If you want every array element to have a different value, you need to create a separate object for each one. That is as simple as moving the SubnetItem ted = new SubnetItem(...); line down a few lines so that it is inside the for loop.

Unable to get values from ArrayList

I have an ArrayList which takes an object.
Handler.java
public ArrayList<LinkedInAccountObject> getAllLinkedInUsersFromDatabase(){
LinkedInAccountObject lao = new LinkedInAccountObject();
counter++;
lao.setAccountId(rs.getLong("account_id"));
lao.setLinkedInAccountId(rs.getString("linkedin_account_id"));
lao.setParentId(rs.getLong("parent_id"));
lao.setFirstName(rs.getString("first_name"));
lao.setLinkedInAccountId(rs.getString("linkedin_account_id"));
lao.setEmail(rs.getString("email"));
lao.setAccessToken(rs.getString("access_token"));
lao.setExpiresOn(rs.getLong("expires_on"));
laoarray.add(counter, lao);
}
My PageLoader.java uses this object to set values
ArrayList<LinkedInAccountObject> laoarray = lndb.getAllLinkedInUsersFromDatabase();
for (LinkedInAccountObject lao : laoarray) {
LinkedInPageObject lpo = new LinkedInPageObject();
lpo.setCompanyID(lao.getParentId());
lpo.setComment(lao.getComment());
//lpo.setDescription(obj.getString("description"));
//lpo.setTitle(obj.getString("title"));
}
But im unable to use the lao object to get the details, getting an null pointer.
when i print the lao object, it gives the result as below,
array objects[null, LinkedInAccountObject [accountId=xxx,
parentId=xx, expiresOn=xxx]]
I would suggest that you replace your loop in the second code with the following:
Iterator<LinkedInAccountObject> iterator = laoarray.iterator();
while(iterator.hasNext()){
LinkedInAccountObject lao = iterator.next()
LinkedInPageObject lpo = new LinkedInPageObject();
lpo.setCompanyID(lao.getParentId());
lpo.setComment(lao.getComment());
//remaining of your code.
}
EDIT
From all the comments that have been posted here I feel that you have initialised the counter variable as 0. In your method getAllLinkedInUsersFromDatabase() you are looping through a loop using rs.hasNext(). Now if this is correct, Then when the first data is being stored, your method creates a new instance of LinkedInAccountObject in lao. Then it goes on to increment counter by 1. So in this case counter was 0 now it becomes 1.
After all your code that you uploaded being executed in the last line it executes laoarray.add(counter, lao);. Here counter being at 1 adds the lao object to the laoarray at position index 1, leaving position index 0 as null. Then it repeats till the end of the ResultSet. This means if your rs variable returned 10 rows, they would be added to laoarray in indices 1 to 10 with 0 index being null.
You could verify if this is happening or not by simply System.out.println("laoarray length = "+laoarray.size()); in your 'PageLoader.java' after you have initialised the laoarray variable.
If this is correct then you could remove the counter++; in the method getAllLinkedInUsersFromDatabase() from its present location and set it after laoarray.add(counter, lao); as shown below:
LinkedInAccountObject lao = new LinkedInAccountObject();
//counter++; remove it from here.
lao.setAccountId(rs.getLong("account_id"));
lao.setLinkedInAccountId(rs.getString("linkedin_account_id"));
lao.setParentId(rs.getLong("parent_id"));
lao.setFirstName(rs.getString("first_name"));
lao.setLinkedInAccountId(rs.getString("linkedin_account_id"));
lao.setEmail(rs.getString("email"));
lao.setAccessToken(rs.getString("access_token"));
lao.setExpiresOn(rs.getLong("expires_on"));
laoarray.add(counter, lao);
counter++;//place it here
Does you counter start at -1? You do counter++ before adding to the arraylist.
This would mean that the first entry is never filled.
You could edit the code to start at index 0, or in the for loop check if the lao isen't null before handeling it.
This code doesn't seem complete but my guess is that you modify counter before adding the item so if you have an array and start with counter = 0 you add the first element to position 1 and position 0 remains null.
Make it:
LinkedInAccountObject lao = new LinkedInAccountObject();
.... fill object values ......
laoarray.add(counter, lao);
counter++;

How to initialize a variable in a do while loop without passing the value until the loop has closed?

I've been writing a program that requires the input of a number between 1 and 4. In order to prevent input of numbers outside the range. However the variable keeps passing to another piece of code and causing the program to fail.
This is the do while loop:
do
{
System.out.println("Please enter a quarter number 1-4: ");
quarter = scanIn.nextInt();
}while((quarter > 5 ) && (quarter < 0));
This is the piece of code that runs the variable:
for (int n = ((quarter * 3)-3); n < (quarter*3); n++)
{
String sum = fmt.format(monthSales[n]);
System.out.printf("Sales for month %d: %s\n", n+1, sum);
}
This is the error that returns when incorrect input is entered:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -6
at lab4.Lab4.main(Lab4.java:57)
I have tried limiting the scope of "quarter" to only within the loop but then the while clause does not function. How can I prevent the variable from passing until the loop has closed?
p.s. This problem is part of an assignment and therefore I must use a do while loop.
I see one thing in your code:
The "do/while" condition seems to be wrong. If your intention is, as I understood, keep asking the user until s/he informs a valid quarter between 1 and 4, the condition should be something like
do {
// ...
} while (quarterNum < 1 || quarterNum > 4);
If I suppose that quarter receives the value of quarterNum in some code in between, the second part seems to be correct and the exception should only occurs if quarter is not a valid value (-1 to be exact). Fixing the do/while condition it will not be possible any more.
I don't see where limiting variable scopes could have anything with your issue. (and I don't even see what you mean by "prevent[ing] the variable from passing until the loop has closed").
I hope I could help you.

Applying Gravity : 2D arrays

My program consists of a grid composed by a 2D array.
The user input deletes certain elements of the grid, leaving blank spaces.
My issue is making the elements above the blank spaces drop down.
Originaly I had an array to check if a space is blank, and if is was blank, the element above would be deleted and recreated where there used to be a blank.
My problem is, the array I used to do this was Left->Right, Top->Down (i++, j++), this leaves me with the problem of having to repeat the whole code to get newly built blank spaces. (For example, if I delete something from the 3rd row, the 2nd row would be blank, but I'd have checked the 2nd row already.
Since it would be very uneffective (including overstack errors) I decided to do the reserve, bottom->top, right->left array (i--,j--), my issue with this is that I'm getting an array out of bounds error, even though I made sure its not possible for it to go out of bounds.
Here is the piece of code which is giving problems
public static void dropBall(){
for (i =Settings.row-1;i>=0;i--){
for (j =Settings.col-1;i>=0 ; j--){
if (i <0||j<0)break;
if (Settings.grid[i+1][j]==666){
//checking if the space below has the 666 ID (666 ID equals to blank)
Settings.grid[i+1][j]=Settings.grid[i][j]; //Deleting the current blank
}
}
}
}
Note:
Settings.row and Settings.col are similar to something.lenght, meaning they have the lenght of the grid, even though the grid starts at 0.
How can I avoid the outofBounds error in this situation?
On line3:
for (j =Settings.col-1;i>=0 ; j--){
change to:
for (j =Settings.col-1;j>=0 ; j--){
and you can remove the if line after.
and start your i on Settings.row-2 instead
try this:
public static void dropBall(){
for (i =Settings.row-1;i>=0;i--){
for (j =Settings.col-1;j>=0 ; j--){
if (Settings.grid[i+1][j]==666){
//checking if the space below has the 666 ID (666 ID equals to blank)
Settings.grid[i+1][j]=Settings.grid[i][j]; //Deleting the current blank
Settings.grid[i][j] = 666;
}
}
}
}
Start from the second row at the bottom, and not from the first (since there is no row below it):
for (i = Settings.row-2 ... // instead of row-1
Remove this line (it is redundant):
if (i <0||j<0)break;

Categories