일부 재귀 메서드에 문제가 있습니다. 나는 표준 입력으로부터 0이 읽힐 때까지 정수의 순서로 읽는 프로그램을 작성하고 그것들을 배열 (0을 포함)에 저장한다. findMax
은 0을 계속 반환하고, countPositive
및 SumDivisibleBy3
은 대부분 몇 시간만큼 꺼져있는 것처럼 보입니다. 어레이를 검색하려면 public static int exists(int[] array, int lastIndex, int searchElement)
을 구현하는 데 도움이 필요합니다.Java 재귀 메서드 - findMax 및 countPositive
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
@ sturcotte06 'findMax','countPositive','computeSumDivisibleBy3' 모두 반복적으로 호출합니다. ** 편집 : ** 죄송합니다, 오독. 당신 말이 맞아요, 재귀적인 문제가되어서는 안됩니다. –
* 재귀적인 문제가 있어서는 안됩니다. –