这通常是完成的方式,但是必须递归地没有for,do-while和while循环。仅if语句。
import java.util.ArrayList;
import java.util.Scanner;
public class arrayex1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Integer> numbers = new ArrayList<Integer>();
System.out.println("Enter numbers: ");
for (int i = 0; i < 10; i++) {
int num = input.nextInt();
numbers.add(num);
}
for (int i = 0; i < numbers.size(); i++) {
if (numbers.get(findMin(numbers)) == i) { // If the 'smallest' index value is equal to i.
System.out.println(numbers.get(i) + " <== Smallest number");
} else {
System.out.println(numbers.get(i));
}
}
}
public static int findMin(ArrayList<Integer> n) {
int min = 0; // Get value at index position 0 as the current smallest.
for (int i = 0; i < n.size(); i++) {
if (n.get(i) < min) {
min = i;
}
}
return min;
}
}
最佳答案
干得好 ...
public static void main(String[] args) throws Exception {
final List<Integer> numbers = new ArrayList<Integer>() {
{
add(3);
add(4);
add(6);
add(1);
add(9);
}
};
final int min = findSmallest(numbers.iterator(), Integer.MAX_VALUE);
System.out.println("Smallest: " + min);
}
private static int findSmallest(Iterator<Integer> iterator, Integer max) {
int min = Math.min(iterator.next(), max);
if (iterator.hasNext()) {
min = findSmallest(iterator, min);
}
return min;
}
关于java - 如何编写将整数的ArrayList作为输入并返回最小整数的递归方法?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15469045/