2014-11-07 1 views
-1

일부 재귀 메서드에 문제가 있습니다. 나는 표준 입력으로부터 0이 읽힐 때까지 정수의 순서로 읽는 프로그램을 작성하고 그것들을 배열 (0을 포함)에 저장한다. findMax은 0을 계속 반환하고, countPositiveSumDivisibleBy3은 대부분 몇 시간만큼 꺼져있는 것처럼 보입니다. 어레이를 검색하려면 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) { 

    //} 
} 
+4

이 그것을하지 재귀 문제. 루프를 사용하십시오. – sturcotte06

+0

@ sturcotte06 'findMax','countPositive','computeSumDivisibleBy3' 모두 반복적으로 호출합니다. ** 편집 : ** 죄송합니다, 오독. 당신 말이 맞아요, 재귀적인 문제가되어서는 안됩니다. –

+2

* 재귀적인 문제가 있어서는 안됩니다. –

답변

0

글쎄, findMax에서 논리가 잘못되었습니다. 당신은 마지막으로 N-1 요소의 최대 값으로 첫 번째 정수를 비교하려면 :

public static int findMax(int[] numbers, int startIndex, int endIndex) 
{ 
    if (startIndex == endIndex) { 
     return numbers[startIndex]; 
    } else {   
     int max = findMax(numbers, startIndex + 1, endIndex); 
     if (numbers[startIndex] < max) { 
      return max; 
     } else { 
      return numbers[startIndex]; 
     } 
    }  
} 

귀하의 countPositive 나에게 올바른 보인다. 아마도 잘못된 입력 매개 변수로 호출 할 수 있습니다.

마지막 방법도 잘못되었습니다. 정지 조건을 확인할 때 endIndex을 사용하지 않습니다.

그것은해야한다 :

public static int computeSumDivisibleBy3(int[] numbers, int startIndex, int endIndex) 
{ 
    if (startIndex == endIndex) { 
     return numbers[startIndex] % 3 == 0 ? numbers[startIndex] : 0; 
    } else { 
     return (numbers[startIndex] % 3 == 0 ? numbers[startIndex] : 0) + computeSumDivisibleBy3(numbers, startIndex + 1, endIndex); 
    } 
} 

은 그냥 exists 방법을 moticed. 우선, 반환 유형을 부울로 변경합니다. 그런 다음 다른 메소드에서 수행 한 작업과 유사한 재귀를 수행합니다. 단일 요소 배열을 특수하게 처리하고 첫 번째 요소의 테스트를 배열의 마지막 n - 1 요소에 대한 재귀 호출과 결합합니다.

public static boolean exists(int[] array, int lastIndex, int searchElement) 
{ 
    if (startIndex == endIndex) { 
     return numbers[startIndex] == searchElement; 
    } else { 
     return (numbers[startIndex] == searchElement) || exists(array, startIndex + 1, endIndex); 
    } 
} 
+0

findMax는 올바르게 작동하지만 존재하는 것은 부울이 아닌 int로 수행되어야하며 startIndex와 endIndex는 작동하지 않습니다. 또한 countPositive를 호출하는 좋은 방법은 무엇입니까? – steelcode

+0

@steelcode 당신은 countPositive를 잘 부릅니다. 존재해야하는 것은 무엇입니까? – Eran

0
public static int computeSumDivisibleBy3(int[] numbers, int startIndex, int endIndex) 
{ 
    if (startIndex==endIndex) { 
     if(numbers[startIndex]%3==0) { 
      return numbers[startIndex]; 
     } else { 
      return 0; 
     } 
    } else { 
     if(numbers[startIndex]%3==0) { 
      return computeSumDivisibleBy3(numbers,startIndex+1, endIndex)+numbers[startIndex]; 
     } else{ 
      return computeSumDivisibleBy3(numbers,startIndex+1, endIndex); 
     } 
    } 
} 
+0

코드 블록을 게시하는 대신 대답을 설명하면 유용 할 것입니다. – Jonathan