Switch to full style
Java2 codes,problems ,discussions and solutions are here
Post a reply

Failing JUnit Tests

Wed Nov 03, 2010 8:47 pm

Failing Junit Tests:
2 parts of my assignment are failing JUnit tests and I don't know why, hoping someone on here can fix them. First part basically-returns 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<|| index>values[(values.length-1)]){
throw new 
IndexOutOfBoundsException();
}
int retValue 0;
for(
int i =0i<values.lengthi++){
if(
values[i]==index){
retValue values[index];
}
}
return 
retValue;


Second Part Code
Code:
public boolean contains(int number) {
boolean retValue false;
for(
int i =0i<values.length-1i++){
if(
values[i]==number){
retValue true;
}else{
retValue false;
}
}
return 
retValue;




Re: Java--What is wrong with my code?

Wed Nov 03, 2010 11:53 pm

hi brother ,
to get element using index i think the function should be like this :
Code:
public int getAt(int index) {
if (
index<|| index>(values.length-1)){
throw new 
IndexOutOfBoundsException();
}
int retValue 0;
for(
int i =0i<values.lengthi++){
if(
i==index){
retValue values[index];
}
}
return 
retValue;
}
 


Re: Java--What is wrong with my code?

Thu Nov 04, 2010 7:59 am

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;
   }   


Post a reply
  Related Posts  to : Failing JUnit Tests
 JUnit Testing of GUIs in Swing     -  
 Free practice tests on SAP and SCM Concepts     -