Abu Khalid Alotaibi - 1 year ago 91

Java Question

I am trying to outline a java recursive implementation for a function which returns true if all the elements in the list are single digit(i.e.<10). Can assume the list only contains positive numbers.

Here is what I have tried, but it keeps returning true even there is a 2 digits number in the list.

import java.util.*;

public class Q3b {

`static boolean allSingleDigit(ArrayList list) {`

if (list.size() == 0)

return false;

else {

int first = (Integer) list.get(0);

list.remove(0);

if (first < 10)

return true;

else

return allSingleDigit(list);

}

}

public static void main(String[] args) {

ArrayList<Integer> list = new ArrayList();

Collections.addAll(list, 4, 25, 3, 2, 3, 1, 3);

boolean res1 = allSingleDigit(new ArrayList(list));

System.out.println("List Contains all single number" + res1);

}

}

any suggestions guys ?

thanks in advance.

Answer Source

I think you might want to flip the logic slightly so that it returns true only when there are no elements left in the array;

```
static boolean allSingleDigit(ArrayList list) {
if (list.size() == 0)
return true;
else {
int first = (Integer) list.get(0);
list.remove(0);
if (first < 10)
return allSingleDigit(list);
else
return false
}
```