Question subject: Java--What is wrong with my code?
Posted: Wed Nov 03, 2010 8:47 pm
Joined: Wed Nov 03, 2010 8:42 pm Posts: 1 Has thanked: 0 time Have thanks: 0 time
2 parts of my assignment are failing junit tests and i dont know why, hoping someone on here can fix them. First part basicallyreturns the element whos position in the list matches the parameter. Second part returns true if the parameter is in the list, false if parameter is not. I know it must be a small logical error in both.
First part code
Code:
public int getAt(int index) { if (index<0 || index>values[(values.length-1)]){ throw new IndexOutOfBoundsException(); } int retValue = 0; for(int i =0; i<values.length; i++){ if(values[i]==index){ retValue = values[index]; } } return retValue; }
Question subject: Re: Java--What is wrong with my code?
Posted: Wed Nov 03, 2010 11:53 pm
Joined: Tue Mar 27, 2007 10:55 pm Posts: 2279 Location: Earth Has thanked: 39 time Have thanks: 61 time
hi brother , to get element using index i think the function should be like this :
Code:
public int getAt(int index) { if (index<0 || index>(values.length-1)){ throw new IndexOutOfBoundsException(); } int retValue = 0; for(int i =0; i<values.length; i++){ if(i==index){ retValue = values[index]; } } return retValue; }
_________________ Currenlty programming with : java , html , php , and javascript . (OCJP-6 certified )
apeter
Question subject: Re: Java--What is wrong with my code?
Posted: Thu Nov 04, 2010 7:59 am
Joined: Wed Nov 03, 2010 3:48 pm Posts: 4 Has thanked: 0 time Have thanks: 1 time
Hello jeriffstive,
it's quite clear that the second code isn't working like expected.
You are iterating over the whole array using a for-loop. Inside the loop you are testing, if the value at position i is equal to the value number. But if you hit the position you don't stop iterating and thats the problem.
Example: your array values contains {1, 3, 5} and you are looking for 3. Your for-loop iterates the three values 1, 3 and 5. The variable retVal will have the following values: for i=0, values[0]=1: retVal = false for i=1, values[1]=3: retVal = true for i=2, values[2]=5: retVal = false and your function will return false.
You have to stop your searching, when you find the element. The correct code would be:
Code:
public boolean contains(int number) { for(int i = 0; i < values.length - 1; i++){ if(values[i] == number){ return true; } } return false; }