I am having a hard time to get this to work. The isLoop() method gets called every time something is added to the array to make sure there are no duplicates. When there is a duplicate, it should return true. But it isn't.
isLoop(){
if(!Arrays.asList(SQUARES).contains(sq)){
return false;
}else{
return true;
}
}
Am I missing something fundamental about arrays? I am fairly new to Java, so it is probably the case! :D
EDIT
I have been asked to show how the objects were instansiated, so I have posted the whole class here:
class Happy {
static int SQUARES[] = new int[10000];
static int sq;
public static boolean isHappy(int num){
int s = 0;
int n = num;
int i=0;
for(sq = num; (!isLoop()) && (sq > 1);){
sq = addSquaresOfDigits(sq);
SQUARES[i] = sq;
i++;
}
if(isLoop()){
return false;
}else{
return true;
}
}
static int addSquaresOfDigits(int number) {
int result = 0;
int tmp;
while(number > 0) {
tmp = number % 10;
result += tmp * tmp;
number /= 10;
}
return result;
}
static boolean isLoop(){
if(!Arrays.asList(SQUARES).contains(sq)){
return false;
}else{
return true;
}
}
The method isHappy() will test the number given it to see whether it is a happy number or not.