我正在编写一个程序,允许用户将一组整数输入到数组中,输入零后将显示这些数字的特征。我有一个方法的问题:findMaxOfLessThanFirst。当然,其中,数组中的最大数量也小于输入的第一个数字。这里是完整的代码:递归方法中的堆栈溢出
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Assignment9 {
public static void main(String[] args) throws IOException {
int index = 0;
int[] numbers;
numbers = new int[100];
InputStreamReader inRead = new InputStreamReader(System.in);
BufferedReader buffRead = new BufferedReader(inRead);
String line = buffRead.readLine();
try {
while (!line.equals("0") && index < 100) {
numbers[index] = Integer.parseInt(line);
index++;
line = buffRead.readLine();
}
} catch (IOException exception) {
System.out.println("Array index out of bound");
}
int min = findMin(numbers, 0);
int sumAtEven = computeSumAtEvenIndexes(numbers, 0, numbers.length - 1);
int divByThree = countDivisibleBy3(numbers, 0, numbers.length - 1);
int maxLessThanFirst = findMaxOfLessThanFirst(numbers, 1, numbers.length - 1, numbers[0]);
System.out.println("The minimum number is " + min);
System.out.println("The sum of numbers at even indexes is " + sumAtEven);
System.out.println("The count of numbers that are divisible by 3 is " + divByThree);
System.out.println(
"The maximum number among numbers that are less than the first number is " + maxLessThanFirst);
}
public static int findMin(int[] numbers, int index) {
if (index == numbers.length - 1) {
return numbers[index];
} else {
return Math.min(numbers[index], findMin(numbers, index + 1));
}
}
public static int computeSumAtEvenIndexes(int[] numbers, int startIndex, int endIndex) {
if (startIndex == endIndex) {
if (startIndex % 2 == 0) {
return numbers[startIndex];
} else
return 0;
} else {
if (endIndex % 2 == 0) {
return computeSumAtEvenIndexes(numbers, startIndex, endIndex - 1) + numbers[endIndex];
} else {
return computeSumAtEvenIndexes(numbers, startIndex, endIndex - 1);
}
}
}
public static int countDivisibleBy3(int[] numbers, int startIndex, int endIndex) {
if (startIndex == endIndex) {
if (numbers[startIndex] % 3 == 0) {
return +2;
} else {
return 1;
}
} else {
if (numbers[endIndex] == 0) {
return countDivisibleBy3(numbers, startIndex, endIndex - 1);
}
if (numbers[endIndex] % 3 == 0) {
return countDivisibleBy3(numbers, startIndex, endIndex - 1) + 1;
} else {
return countDivisibleBy3(numbers, startIndex, endIndex - 1);
}
}
}
private static int findMaxOfLessThanFirst(int[] numbers, int startIndex, int endIndex, int firstNumber) {
if (startIndex == endIndex) {
if (numbers[endIndex] <= firstNumber)
return numbers[startIndex];
}
int max = findMaxOfLessThanFirst(numbers, startIndex, endIndex - 1, firstNumber);
if (max >= numbers[endIndex] && max <= firstNumber) {
return max;
}
return numbers[endIndex];
}
}
我相信我在这里错过了一些非常基本的东西。我刚开始学习递归的概念。所以,请温柔。
这个问题已经被问过,虽然它没有一个完整的答案http://stackoverflow.com/questions/43148782/how-to-find-a-maximum-number-thats-less-但是它看起来像是一个家庭工作问题,而“提问者”却没有给予足够的时间。 – iavanish
只把代码放在你面对问题的地方,这样对其他人来说很容易阅读。 – Omore
有人问完全相同的问题,今天我想。 – efekctive