2016-10-22 2 views
0

부울 메서드를 사용하여 완벽한 숫자를 찾으려면 Java 코딩에 문제가 있습니다. 나는 다음과 같이 출력하고 싶습니다 : 예 : '6은 완벽한 숫자입니다. 6은 1, 2, 3 '의 합계입니다. 그렇지 않은 경우 : '9는 완벽한 숫자가 아닙니다.부울을 사용하여 완벽한 숫자 확인

그러나 "6은 1, 2, 3의 합계입니다. ". 누구든지 나를 도울 수 있습니까?

import java.util.Scanner; 

public class trial 
{ 
    public static void main(String[] args) 
    { 
     // TODO Auto-generated method stub 

     Scanner perfect = new Scanner(System.in); 
     System.out.print("Enter any integer number : "); 
     int n = perfect.nextInt(); 

     if(isPerfectNumber(n)) 
     { 
      System.out.println(n+" is a perfect number"); 

     } 
     else 
     { 
      System.out.println(n+" is not a perfect number"); 
     } 
    } 

    public static boolean isPerfectNumber(int n) 
    { 
     int sum = 0; 
     for (int i=1; i<n; i++) 
     { 
      if (n%i == 0) 
      { 
       sum = sum + i; 
      } 
     } 
     if (sum == n) 
     { 
      return true; 
     } 
     else 
     { 
      return false; 
     } 
    } 
} 

답변

1

글쎄, 당신은 이미 가 어떻게 if (n%i == 0) 라인에 따라, 수의 요소를 얻는 방법을 알고 다음은 내 코드입니다.

그래서 거의 확실하게 클래스 작업이므로 힌트를 얻으십시오.

같은 시점에 합계에 요소를 추가 할 경우 해당 요소를 설명 목록에 추가하고 호출 함수에서 사용할 수 있도록해야합니다.

하나의 가능성은 목록을 반환하는 것이고 두 번째 및 후속 요소는 주어진 숫자의 모든 요소이며 첫 번째 요소는 그 합계입니다.

그래서, 6를 들어, 목록 {6, 1, 2, 3}, 12 당신에게 {16, 1, 2, 3, 4, 6}을 줄 것이며, 7 당신에게 {7, 1}을 줄 것을 얻을 것입니다.

그런 식으로 첫 번째 요소와 원래의 요소를 비교하고 다른 요소를 인쇄하면됩니다. 즉, 의사 코드 등에서 : 계수에 해당하는 경우 for 루프에서 잘

input num 
factorList = getFactorList(num) 
if factorList[0] == num: 
    print num, " is perfect, factors are:" 
    for idx = 1 to factorList.size() - 1 inclusive: 
     print " ", factorList[idx] 
    println "." 
else: 
    println num, " is not perfect." 
0

조건 다음은 i 어떻게 든 트랙에 보관해야합니다 알고 있다면.

그래서 정수의 arraylist를 선언하여 합계를 추적합니다.

ArrayList<Integer> numbs = new ArrayList<Integer>(); 

그런

public static boolean isPerfectNumber(int n) 
{ 
     int sum = 0;    
     for (int i=1; i<n; i++) 
     { 
      if (n%i == 0) 
      { 
       numbs.add(i); //here keep track of those summation numbers 
       sum = sum + i; 
      } 
     } 
     if (sum == n) 
     { 
      return true; 
     } 
     else 
     { 
      return false; 
     } 
} 

이제

System.out.println(n + " is a perfect number. " + n + " is sum of " + StringUtils.join(numbs, ",")); 

같이 할 수있는 인쇄하는 인 StringUtils를 가져올 것을 잊지 마십시오 동안 : import org.apache.commons.lang3.StringUtils commons-lang3 라이브러리를.

+0

: 그럼 당신은 모두 요소를 포함하고 n 완벽 여부를 결정하는 데 사용할 수있는 하나의 결과가? 코드는 다음과 같이됩니다 : – FAT

+0

import java.util.Scanner; import org.apache.commons.lang3.StringUtils; 공용 클래스 테스트 { \t 공공 정적 무효 메인 (문자열 []에 args) { \t \t \t // TODO 자동 생성 방법 마취 = 새로운 ArrayList를 () \t \t ArrayList를 스터브; \t \t 스캐너 완전 = 새 Scanner (System.in); \t \t System.out.print ("임의의 정수 입력 :"); \t \t int n = perfect.nextInt(); \t \t \t \t 경우 (isPerfectNumber (N)) { \t \t \t \t \t 에서 System.out.println (N + "완전한 번호는"); \t \t \t "System.out.println (n +"은 "+ StringUtils.join (numbs,", "))의 합계입니다. 다른 \t \t} \t \t \t \t { \t \t에서 System.out.println (N + "완벽한 숫자가 아닌"); \t \t \t}} – FAT

+0

공공 정적 부울 isPerfectNumber (INT 않음) \t \t \t {INT 합 = 0; \t \t 찾는 (나는은 N <; I = 1 int로 난 ++) \t \t { \t \t \t 경우 (N % I == 0) \t \t \t { \t \t \t \t numbs.add (I); \t \t \t \t sum = sum + i; \t \t \t \t \t }} \t \t 경우 (합계 == N) \t \t \t \t { \t 참을 리턴; 거짓 다른 \t \t} \t \t \t \t { \t \t \t 반환; \t \t } – FAT

1

나는 그것이 완전 수 아니라면 n 또는 null을 구성하는 요소의 List을 반환 isPerfectNumber을 변경할 것입니다. 난 당신이 나에게 무엇을 제안하고 있습니다 않았다 그런데 왜 난 아직도 내 프로그램에서 몇 가지 오류를 발견 할

public static void main(String[] args) { 
    Scanner perfect = new Scanner(System.in); 
    System.out.print("Enter any integer number : "); 
    int n = perfect.nextInt(); 

    List<Integer> factors = getPerfectFactors(n); 
    if (factors != null) { 
     System.out.println 
      (n + " is a perfect number. It's the sum of" + 
      factors.stream() 
        .map(String::valueOf) 
        .collect(Collectors.joining(", ")); 
    } else { 
     System.out.println(n+" is not a perfect number"); 
    } 
} 

public static List<Ingeger> getPerfectFactors(int n) { 
    int sum = 0; 
    List<Ingeger> factors = new LinkedList<>(); 
    for (int i = 1; i < n; i++) { 
     if (n % i == 0) { 
      sum += i; 
      factors.add(i); 
     } 
     if (sum > n) { // Early return optimization, not material to the solution 
      return null; 
     } 
    } 
    if (sum == n) { 
     return factors; 
    } else { 
     return null; 
    } 
} 
+0

이지만이 문제를 해결하기 위해 부울 메서드를 사용해야한다. – FAT