This is my code snippet:
public NaturalNumberTuple toSet()
{
int newTuple[] = new int[tuple.length];
boolean checkIfYouHadToRemoveSomething = false;
for(int i : newTuple){
newTuple[i] = tuple[i];
}
for(int i : newTuple){
for(int j : tuple){
if(newTuple[i] == tuple[j]){
NaturalNumberTuple placeholderTuple = remove(tuple[j]);
newTuple[i] = tuple[j];
checkIfYouHadToRemoveSomething = true;
}
}
}
if(checkIfYouHadToRemoveSomething){
return placeholderTuple;//Problem
} else {
return new NaturalNumberTuple(tuple);
}
}
The method is returning a new NaturalNumberTuple without the given Number (here tuple[j]).
My toSet() method should give me the same Array as I'm giving to it but with only one occurrence per number.
My problem is in the line marked with (//Problem).
The Problem is that placeholderTuple is not defined as a variable. I know it isn't, but if I write at the beginning of my method:
NaturalNumberTuple placeholderTuple;
and at the line where I originally defined my placeholderTuple:
placeholderTuple = remove(..);
it gives me an error that placeholderTuple may not been initialized yet.
I know why I'm getting those errors but I really don't know how to fix that.
If anyone is trying to optimize my code with ArrayLists, please don't because I'm not allowed to use them (not sure if they would help here but at other code snippets they would).
At the start of your method, write :
NaturalNumberTuple placeholderTuple = null;
This will keep this variable visible till the end of the method, and initialize it to a default value.
Then, inside the loop yo change :
NaturalNumberTuple placeholderTuple = remove(tuple[j]);
to
placeholderTuple = remove(tuple[j]);
Declare and initialize it in the begining of the code as:
NaturalNumberTuple placeholderTuple = null;
And in your loop, just initialize it without redefining like placeholderTuple = remove(tuple[j]); and it should work.
I think your code will always return the last entry of newTuple which is similar to tuple, so it doesnt makes sense to me. If you just want to remove very first match, you could do without two loop like:
placeholderTuple = remove(tuple[0]);
Related
A segment of my code is triggering an infinite while loop, and I'm not sure why. I've used the loop itself before to add friends to a Linked List in this same program and it worked fine, so I do not understand why it is turning into an infinite loop now.
while (!a.equals("*")){
curr = friendlist.getUsers().getFront();
while (curr!=null){
if (curr.getData().getName().equals(a)){ //why is it not removing friends?
d.removeFriend(curr.getData());
}
curr = curr.getNext();
}
System.out.println("Add a friend by typing in their name. Enter * to end. ");
a = in.nextLine();
}
The above code accesses the following segment from another class:
public void removeFriend(User u){
if (friendsList.isEmpty()){
System.out.println("Empty list, cannot remove.");
}
else{
Node c = friendsList.getFront();
while (c.getNext()!=null){
if (c.getNext().getData().equals(u)){ //condition: if the data is the same
c.setNext(c.getNext().getNext()); //change the link
c.getNext().setData(null); //set the next data to null (cut the link)
friendsList.setSize(friendsList.size()-1);
c = c.getNext();
}
}
}
}
Why is the code not running properly?
As another poster has mentioned, you are invoking the getNext() method twice in one code block.
Here's what I presume is what will work for you
while (c!=null){
if (c.getNext().getData().oldestFriend().getBirthYear()>c.getData().oldestFriend().getBirthYear()){
a = c.getNext().getData();
continue; //then skip the current iteration, so that your line below after the if statement, wont get called.
}
c = c.getNext();
}
Why dont you do this, because now it looks like you're calling that same method three times!
Instead, store whatever is returned from the getNext() into one variable, and then access that local variable and do whatever you want with it, analyse is however you like etc.
Do you know where the infinite loop is exactly? Maybe put a System.out.println("loop") before curr.getNext() and c.getNext() so see which one is failing?
Would add this as a comment, but I'm not yet allowed to :(
How is the semantic of
allUsers.getFront()
Does it just fetch the head or is it more like a pop-operation?
In case of a fetch, there might be an issue with the recursive call of
oldestFriend()
in the method oldestFriend().
Though in that case I would expect a StackOverflowException.
change your while by:
while (c.hasNext() {
Node oldC = c;
c = c.getNext();
if(c.getData().oldestFriend().getBirthYear() > oldC.getData().oldestFriend().getBirthYear()) {
a = c.getData();
}
}
Call only getNext() if there is next, and only once.
I'm having some difficulty with this for-loop in java:
public String[] geefAlleTemplateNamen(String[][] templateLijst){
for(int i = 0; i < templateLijst.length; i++){
String lijst[] = {templateLijst[i][0]};
}
return lijst;
}
When i execute the program, i get the following error:
Mailmatcher.java:39: error: cannot find symbol
return lijst;
^
symbol: variable lijst
location: class Mailmatcher
1 error
I think this is because 'lijst' is declared inside the for loop, so it's unknown outside it, although i think i know what the problem is, i've got no idea how to solve this.
Any ideas would be appreciated!
I used the search allready, but didn't realy find something, this is a school project, so i don't expect pre-made answers.
Thank you!
You have to declare the lijst[] outside of the loop and fill the array within the loop:
String lijst[] = new String[templateLijst.length];
for(int i = 0; i < templateLijst.length; i++){
lijst[i] = templateLijst[i][0];
}
return lijst;
To add to the answer from kocko, it's because the scope of the list is confined to within the loop. Which will cause two problems,
The list gets redeclared as a new empty list for each iteration of the loop (wiping out any previously stored data)
The return is outside of the loop, so it can't access the list, it pretty much no longer exists once your code completes the loop and moves on.
So yes, declare the list before the loop.
I am having a list of queues as follows:
public class QueueSelection {
public List initQueueCollection()
{
QueueLoad d1 = new QueueLoad("QUEUEA1", "QUEUEB1", true);
QueueLoad d2 = new QueueLoad("QUEUEA2", "QUEUEB2", false);
QueueLoad d3 = new QueueLoad("QUEUEA3", "QUEUEB3", true);
QueueLoad d4 = new QueueLoad("QUEUEA4", "QUEUEB4", false);
List list = new ArrayList();
list.add(d1);
list.add(d2);
list.add(d3);
list.add(d4);
return list;
}
Now from the main method, i call the above method like,
QueueSelection selection = new QueueSelection();
List<QueueLoad> queueList =selection.initQueueCollection();
When the first input/file comes, queue is checked to see which one of these is false, so I am fetching the second one ("QUEUEA2", "QUEUEB2", false);
As soon as I fetch it, I should change the status to true like ("QUEUEA2", "QUEUEB2", true); I am doing it using
for (QueueLoad s:queueList)
{
if(s.getStatus()==false)
{
str1=s.getQueueName1();
str2=s.getQueueName2();
str3=s.getStatus();
particularCollection=s;
System.out.println(s);
particularCollection.setStatus(true);
particularCollection.setQueueName1(str1);
particularCollection.setQueueName2(str2);
int j=queueList.indexOf(particularCollection);
System.out.println("The index is"+j);
s = new QueueLoad(str1, str2, true);
newqueueList=queueList.set(j, s);
And the list is updated. Now when the second input comes, since in the first line it is seeing the List<QueueLoad> queueList =selection.initQueueCollection();
it is always getting the old list and not the updated one.
Please help.
Now when the second input comes, since in the first line it is seeing
the List queueList =selection.initQueueCollection(); it is
always getting the old list and not the updated one.
I interpret this to mean that you don't want the init method to be invoked again 'when the second input comes'.
There are a lot of ways to address this. Have you considered moving the init method into the constructor for QueueSelection, for example?
Take a look at the javadocs for ArrayList.set. It returns the old value at that location. So you'll want to do:
queueList.set(j, s);
newqueueList = queuelist;
If I have understood you correctly then you're problem is that at each new input you are intializing a new list. Maybe just put queueList as class attribute?
Also:
newqueueList=queueList.set(j, s);
I think set() returns the object that was previously at that index. So your newqueueList would actually contain a QueueLoad object.
Since you haven't shown your main() method, I'm not certain what it looks like, but something along these lines should work:
Instead of:
QueueSelection selection = new QueueSelection();
List<QueueLoad> queueList =selection.initQueueCollection();
Declare queueList outside the method something like this:
private static List<QueueLoad> queueList = null;
Then, in the method,
if (queueList == null)
{
QueueSelection selection = new QueueSelection();
queueList =selection.initQueueCollection();
}
So I have a class full of junit tests and a class full of methods that perform binary operations. The tests are checking to see if I have the right values at certain points.
I am failing a lot of tests because of what I believe to be is the return type. For example I get the message
junit.framework.ComparisonFailure: null expected:<[000]> but was <[BinaryNumber#4896b555]>
If I'm understanding this it's saying that it was looking for an array containing 000 but it got a BinaryNumber (which is the required return type). To help clarify here is one of the methods.
public BinaryADT and(BinaryADT y) {
int[] homeArr = pad(((BinaryNumber) y).getNumber());
int[] awayArr = ((BinaryNumber) y).pad(getNumber());
int[] solution = new int[awayArr.length];
int i = 0;
String empty = "";
while(i < solution.length){
solution[i] = homeArr[i] & awayArr[i];
i++;
}
for(int indexF = 0; indexF < solution.length; indexF++){
empty = empty + solution[indexF];
}
System.out.println(empty);
return new BinaryNumber(empty);
}
Am I understanding this right? If not could someone please explain? I'd also like to point out that this is for my homework but I'm not asking for answers/someone to do it for me. Just a point in the right direction at most.
I will gladly clarify more if it is needed (I didn't want to bog everything down).
Also this is my first post on here. I tried to keep to the formatting suggestions but I apologize if anything is sub-par.
As suggested here is the test method
public void testAnd1()
{
BinaryADT x = new BinaryNumber("111");
BinaryADT y = new BinaryNumber("000");
BinaryADT z = x.and(y);
assertNotSame(x,z);
assertNotSame(y,z);
assertEquals("000",z.toString());
}
Whenever you see the output of "toString()" like ClassName#SomeNumber, then you can be sure that toString() method is not implemented for that class (unless toString() method implementation itself is not like this).
In your case, expected value is [000], but you are getting [BinaryNumber#4896b555].
Try to implement toString() method in BinaryNumber class and return the value from this method as per assertEquals() expects. This should solve the problem.
Can you show me your test code?
1.Your expected type is different from the actual type.
2.BinaryADT class didn't overide toString method.
A while back, I was working on a program that hashed values into a hashtable (I don't remember the specifics, and the specifics themselves are irrelevant to the question at hand). Anyway, I had the following code as part of a "recordInput" method:
tempElement = new hashElement(someInt);
while(in.hasNext() == true)
{
int firstVal = in.nextInt();
if (firstVal == -911)
{
break;
}
tempElement.setKeyValue(firstVal, 0);
for(int i = 1; i<numKeyValues;i++)
{
tempElement.setKeyValue(in.nextInt(), i);
}
elementArray[placeValue] = tempElement;
placeValue++;
} // close while loop
} // close method
This part of the code was giving me a very nasty bug -- no matter how I finagled it, no matter what input I gave the program, it would always produce an array full of only a single value -- the last one.
The problem, as I later determined it, was that because I had not created the tempElement variable within the loop, and because values were not being assigned to elementArray[] until after the loop had ended -- every term was defined rather as "tempElement" -- when the loop terminated, every slot in the array was filled with the last value tempElement had taken.
I was able to fix this bug by moving the declaration of tempElement within the while loop. My question to you, Stackoverflow, is whether there is another (read: better) way to avoid this bug while keeping the variable declaration of tempElement outside the while loop.
Why would you want to keep the variable declaration outside the while loop? Anyway, you can, as long as you assign it to a new hashElement each time:
hashElement tempElement;
while (/*...*/) {
tempElement = new hashElement();
//...
It's certainly not "better" though. Scope your variables as narrowly as possible, in general.
This is not about declaration of the variable, but about the objects you create. Arrays in java only hold references to objects, so if you actually want to have distinct objects in the array, you need to create them with new somewhere in the loop.
tempElement = new WhateverClass();
Element tempElement;
while(condition){
tempElement = new HashElement();
//do more stuff
elementArray[index] = tempElement;
}