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(ie<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.
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
}
Your program seems fine, only problem is you should return false
as soon as first element >= 10
is encountered and return true
when list size is 0
. Modify it as shown below:
static boolean allSingleDigit(List<Integer> list) {
if (list.size() == 0)
return true;
int first = list.remove(0);
if (first == null || first >= 10)
return false;
else
return allSingleDigit(list);
}
You could optimize it and make it more concise by using generic List
and using remove()
method from List
directly. I have also added missing null
check.
I think this is the method you wanted.
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 false;
else
return allSingleDigit(list);
}
}
I have just changed in your code.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.