【发布时间】:2014-11-07 04:00:06
【问题描述】:
我遇到了一些递归方法的问题。我正在编写一个程序,它从标准输入读取整数序列,直到读取到 0,并将它们存储在数组中(包括 0)。 findMax 一直返回 0,而 countPositive 和 SumDivisibleBy3 似乎大部分时间都偏离了几个数字。我还需要帮助实现 public static int exists(int[] array, int lastIndex, int searchElement) 来搜索数组。
import java.io.*;
public class Assignment9 {
public static void main(String[] args) throws IOException {
int i = 0;
int [] nums;
nums = new int [100];
InputStreamReader inRead = new InputStreamReader(System.in);
BufferedReader buffRead = new BufferedReader(inRead);
String line = buffRead.readLine();
try {
while (line.equals("0") == false && i<100) {
i++;
line = buffRead.readLine();
nums[i]=(int) Double.parseDouble(line);
}
} catch(IOException e) {
System.out.println("Array index out of bound");
}
int findM = findMax(nums, 0, nums.length-1);
int countP = countPositive(nums, 0, nums.length-1);
int divis3 = computeSumDivisibleBy3(nums, 0, nums.length-1);
System.out.println("The maximum number is: " + findM);
System.out.println("The count of positive integers is " + countP);
System.out.println("The sum of the numbers divisible by 3 is " + divis3);
}
public static int findMax(int[] numbers, int startIndex, int endIndex)
{
int max = 0;
if (startIndex == endIndex) {
return numbers[startIndex];
} else if (numbers[startIndex] < numbers[endIndex]) {
return findMax(numbers, startIndex + 1, endIndex);
} else {
return numbers[startIndex];
}
}
public static int countPositive(int[] numbers, int startIndex, int endIndex)
{
if (startIndex == endIndex) {
if (numbers[startIndex] > 0)
{
return 1;
}
else
return 0;
} else {
if (numbers[startIndex] > 0)
{
return 1 + countPositive(numbers, startIndex +1, endIndex);
}
else
return countPositive(numbers, startIndex +1, endIndex);
}
}
public static int computeSumDivisibleBy3(int[] numbers, int startIndex, int endIndex)
{
if (startIndex == numbers.length - 1) {
return numbers[startIndex] % 3 == 0 ? numbers[startIndex] : 0;
} else {
return (numbers[startIndex] % 3 == 0 ? numbers[startIndex] : 0) + computeSumDivisibleBy3(numbers, ++startIndex, endIndex);
}
}
// public static int exists(int[] array, int lastIndex, int searchElement) {
//}
}
【问题讨论】:
-
这不是递归问题。使用循环。
-
@sturcotte06 在我看来是递归的:
findMax、countPositive和computeSumDivisibleBy3都以递归方式调用自己。 编辑:抱歉,误读了。你是对的,它不应该是一个递归问题。 -
它不应该是递归问题。
-
在我打赌 OP 正在学习的编程课程的上下文中,这是一个递归问题。不,我们不会为你做作业。
-
从来没有说过代码没有递归性,但是,递归处理它是最糟糕的实现。拥有超过 500 个元素,并确保遇到堆栈溢出异常。
标签: java arrays recursion bufferedreader