Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Here's a brief explanation of my program:
User keys in data
Data is stored in vector
User may choose to key in data again...
Before the program is closed, a summary screen of data will be displayed.
The problem I'm facing now is that the for loop is executed even before data is stored in it, while what I want is for the for loop to run only summary screen is displayed.
Is there a way to tackle this problem?
SummaryPanel.class (Partial code)
list = new JList<String>();
scroll = new JScrollPane(list);
model = new DefaultListModel<String>();
for(int i=0; i<con.retrievePersonalVector().size(); i++){
model.addElement(((PersonalRecord)con.retrievePersonalVector().get(i)).getLoginName()); //NPE
list.setModel(model);
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
int selected = list.getSelectedIndex();
}
});
A couple of things:
Vector<?> persRecs = con.retrievePersonalVector();
for (int i = 0; i < persRecs.size(); i++) {
PersonalRecord persRec = (PersonalRecord)persRecs.get(i);
if (persRec != null) (
model.addElement(persRec.getLoginName());
}
}
In the original code the retrievePersonalVector was done at every loop step twice: checking the size and getting an element. Instead of 2N times, retrieval is now done once.
Then the model was passed to the component in the loop. Mabye a genuine decision, to see a something, but that probably does not work here, hence I close the loop early. Also adding a listener should be done once. (Or you maybe lost a } on copying together the question.
First of all, you should not use Vector anymore. Prefer List<T> list = Collections.synchronizedList(new ArrayList<T>()). Secondly, if the NullPointerException is indeed thrown where you spot it, it is probably because the Vector contains some null elements, so you should insure that you do not store any null element. Last, why not checking if the summary panel is displayed before looping (either with an isVisible() or a local boolean) ?
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am currently practicing with my coding skills and one of the challenges I ran into was finding the first duplicate value produced in an array. I had solve the challenge, but not in a timely manner. I looked at the solution for the problem and ran into this solution and wanted help in understanding how it exactly works. I have the solution commented in the areas that I understand and what exactly is the purpose of that block of code, but I would like help in understanding the if-statement why it works the way it does.
int firstDuplicate(int[] a) {
for(int i=0;i<a.length;i++)
//Checks ???????????
if(a[Math.abs(a[i])-1]<0)
return Math.abs(a[i]);
//Make the checked value negative
else{
a[Math.abs(a[i])-1]=-a[Math.abs(a[i])-1];
}
//If there are no duplicates it returns -1
return -1;
}
Constraints:
1 ≤ a.length ≤ 105,
1 ≤ a[i] ≤ a.length.
Welcome to SO. I will not give you the exact answer but instead provide you with tools for you to figure it out.
In order for you to figure out this code, you need to debug it. Here are some ways you could go about it.
Set a breakpoint just prior to calling the function (look up how to do this for your IDE), thereafter step into your code line-by-line.
You could use a combination of temporary variables and System.out.println() statements. Looking into your code, break it down into modular bits that you can track. For instance you could re-write the expression inside the if statement as
int currentElementAbsolute = Math.abs(a[i]);
System.out.println(currentElementAbsolute);
int difference = currentElementAbsolute - 1;
System.out.println(difference);
int element = a[difference]
System.out.println(element);
if (element < 0)
{
return Math.abs(a[i]);
}
As you can see, for each operation/line, I print out the current value thus keeping track of events. Practice this and re-write the else part
PS: Upon completion you will realise this method fails to capture all duplicates when certain type of numbers are used. Happy Hunting :)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
My code executes properly only when it is not placed within the if statement. Why is that happening? I think there has to be something wrong with the condition which is supposed to check if Strings which are coming from JTextFields aren't empty.
Here is my code which is working without using the if statement:
user1.name = name1;
user1.password = pass1;
user1.ip = i1;
save(user1);
And here is the badly implemented if statement:
if(!name1.equals("") && !pass1.equals("") && !i1.equals("")) {
user1.name = name1;
user1.password = pass1;
user1.ip = i1;
save(user1);
}
Note: name1, pass1 and i1 are all Strings of pretty basic values. name1 can be Bob, pass1 can be Bob123 and i1 can be 192.168.32.1
Since you are trying to
check if Strings which are coming from JTextFields aren't empty
check the doc for the isEmpty() method and use something like:
if((name1 != null && !name1.isEmpty()) &&
(pass1 != null && !pass1.isEmpty()) &&
(i1 != null && !i1.isEmpty()) ) {
//....
}
A distinct non-answer: you are doing the validation in the wrong place!
Your UI elements should only allow you to trigger that save action when the required values are present. Create a user experience that prevents the user from making mistakes. Instead of investing times to discover "oh, the user made a mistake"!
In other words: you should listen to status changes on your text fields, and only when all three textfields have an non empty content, only then, you enable your Save button/menu item! And when one of field turns empty again, you better disable that button/menu item.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have this code
for (int i=0; i<tini.length; i++){
tini[i].tempLabel.setText("Temp: "+ Float.toString(tempArray[i]) +"°" );
out_status[i] = tini[i].alarm;
frame.statusLabel.setText("Connetction: OK, String: OK");
}
System.out.println("old: " + Arrays.toString(out_status_old));
System.out.println("new: " + Arrays.toString(out_status));
if (Arrays.equals(out_status, out_status_old) ){
System.out.println("UGUALI");
}
out_status_old = out_status;
the resulting arrays are always equal. I cannot understand the reason.
Using a Button in JFrame, in a GUI interface i can modify the value of alarm, but both the old value and the actual one change at the same time!
When you access and then update the elements of one array, you're also updating the elements of the other array because they are referencing the same objects. You need to create separate items within each array while populating the arrays.
You left out an important part of your program which is where you're actually populating these arrays. Odds are, you are not doing a deep copy.
Deep copy of an object array
The line out_status_old = out_status; does not create a copy of the array. You have just two variables, out_status and out_status_old, pointing to the same array.
If you want to create a proper copy of the array, you can e.g. use Arrays.copyOf (or one of its variants).
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Does anyone know how can I populate an array that checks if the positions are filled before filling them, and if they are already filled and if that array position is filled it increments to the next one.
Thanks
Primitive array elements are never empty. For example in an int array all elements will be initialized to 0.
So if you want to check for filled or not, initialize the array elements to a value which it is not going to take. say -1. Then each time you make an entry check for -1. The dummy value initialization is necessary as you can not check for 0, because 0 can be a valid data as well
// Initialization part
int [] arr= new int [17];
for(int i=0;i<arr.length;i++)
{
arr[i]= -1;
}
Hope you will do the checking part yourself
I am assuming (possibly incorrectly) that you either a) want a method that inserts object into the first available (i.e. not null) spot in the array at or past the argument integer or b) want to insert repeatedly into the array using the method in a)
the method in a) would basically be as follows
public <Type> void myInsertMethod(Type[] array,Type item,int position)
{
while (array[pos]!=null)
{pos++;}
array[pos]=item;
}
if you want to do this repeatedly on the same array, just call the method repeatedly, with different positions and items.
You can check if the position you are going to fill it's not null, or empty, or at least the stored value it's different to the one you are going to put
if(array.get(index) != "" && array.get(index) != null) && array.get(index) != newObject){
array.add(newObject);
}
Then, depending on the stored value type, you can ddo some more checks, for example in the cas e of the int, as RookieB says, you can check if the object is different to 0
Hope it helps
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
ive hit a road block and im stuck with a question on my work.
Here is the question:
Provide an implementation of the getLoad method that adds up the individual weights of
the items in the items list and returns the total.
The items list is:
ArrayList<Item> items;
Ive done what i thought was right but for some reason its not working.
Any help on what is wrong, or if what im doing is wrong? thanks
#Override
public int getLoad() {
int load = 0; //declare the variable
for (Item i : items) { // for each item in the list of items
load = load + i.getWeight() ; // load equals the weight of the item and adds on
}
return load; //returns it
}
The one thing I could see going wrong is if getWeight() returns a double. In that case, you should make int load: double load instead
With the limited information you've provided here, I can only take a wild guess that the problem is either:
The list items is empty even though it shouldn't be. Make sure that Items actually get added to the list! Use a debugger or a printed message to find out if the item list is empty on getLoad().
Weights for each Item are not assigned correctly, so getWeight() returns zero for each of them. Make sure that each Item added to the list actually gets assigned its proper weight.
Posting more code would help us give a better answer.