2014-12-03 2 views
0

클래스는 방금 함수 및 메서드가 포함 된 형식으로 코드를 작성하는 방법을 배우기 시작했으며 이것이 처음 시도한 것입니다. 나는 혼란스러워합니다.함수/메서드 및 배열

할당은 임의로 선택된 숫자에 1의 풀을 만들고 배열에 풀을 저장하는 것입니다. 그런 다음 풀을 인쇄하십시오. 사용자는 풀에서 번호를 선택하고 프로그램은 그 번호의 제수를 찾아 인쇄 할 다른 배열에 저장합니다.

제수를 얻고 새로운 배열에 저장 한 다음 배열을 인쇄하는 데 문제가 있습니다.

import java.util.Scanner; 
import java.util.Random; 

public class GetDivisors { 
    public static void main (String[] args){ 
     Scanner read = new Scanner(System.in);    
     int  []pool = new int[100]; 
     int  []divisors = new int[100]; 
     int  size; 
     int  pick; 
     int  numDivisor; 

     // Program Heading 
    printProgramHeading(); 

     // Input and test 
    size = createPool(pool); 
    printPool(pool, size); 

    System.out.println(); 
    System.out.println(); 
    System.out.println("Enter a non-prime value listed in the pool above: "); 
    pick=read.nextInt(); 

     // Data Processing 
    numDivisor = getDivisors(pool, divisors, pick); 

     // Output Section 
    printDivisors(divisors, size, pick);  

    } // end main 

     // Function and Method Specifications 
    // Name   : printProgramHeading 
    // Description : This method prints the program heading to the monitor in all caps and with  a dividing line 
    //    : followed by a blank line. 
    // Parameters : None. 
    // Return  : None. 
    public static void printProgramHeading() { 
     System.out.println("\tGET DIVISORS"); 
     System.out.println(" ************************"); 
     System.out.println(); 
    } // end printHeading 


    //Name   : createPool 
    //Description : This funtion generates an array of consecutive integers from 1 to a randomly  generated 
    //    : number no greater than 100. 
    //Parameters : An integer array. 
    //Return  : An integer (the randomly generated number), representing the size of the array. 
    public static int createPool(int[]pool) { 
     Scanner read = new Scanner(System.in); 
     Random random = new Random(); 
     int size=0; 

     size=random.nextInt(100)+1; 
     pool=new int[size]; 

     return(size); 
    } // end createPool 


    //Name   : printPool 
    //Description : This method prints the pool of numbers to the monitor no more than 10 per line. 
    //Parameters : The pool array, and the size of the pool in that order. 
    //Return  : None. 
    public static void printPool(int[] pool, int size) { 
     int index; 
     int count=0; 

     for(index=1; index<size; index++){ 
      System.out.print(pool[index]=index); 
      System.out.print(" "); 
      count++; 
      if(count == 10){ 
       System.out.println(); 
       count=0; 
      } // end if loop 
     } // end for loop 
    } // end printPool 


    //Name   : getDivisors 
    //Description : This funtion stores all the divisors of the user's pick into the divisor array. 
    //Parameters : The pool array, the divisor array, and the user's pic, in that order. 
    //Return  : The number of divisors found. 
    public static int getDivisors(int[] pool, int[] divisors, int pick){ 
     int numDivisors = 0; 
     int index = 0; 

     for(index=1; index <= pick; index++){ 
      if(pick % index == 0){ 
       numDivisors++; 
       divisors[index] = index; 
      } // end if loop 
     } // end for loop 
     return(numDivisors); 
    } // end getDivisors 


    //Name   : printDivisors 
    //Description : This method prints the contents of the divisors array to the monitor all on one line with 
    //    : a leading label. 
    //Parameters : The divisor array, an integer representing the number of divisors. and the  user's pick 
    //    : in that order. 
    //Return  : None. 
    public static void printDivisors(int[] divisors, int size, int pick){ 
     int index = 0; 

     System.out.println("The divisors of " + pick + ": " + divisors[index] + " "); 
    } // end printDivisors 

} // end class 

고맙습니다!

+0

'getDivisors()'의'for' 루프가 정확히 무엇을 기대하는지 기술하십시오. –

+0

약수를 얻으려면 풀 시작 부분에서 시작하여 사용자가 선택한 번호로 이동하십시오. 풀 번호로 나눈 값의 수가 0 인 경우 풀 번호는 제수입니다. 그런 다음 다음 단계에서 인쇄 할 수있는 배열에 저장해야합니다. 프로그램을 실행하고 약수를 인쇄하려고하면 약수 목록 대신 0이 생깁니다. – kp03

+0

새로 생성 된 배열 ('divisors')의 어떤 요소에도 절대 값을 할당하지 않습니다. –

답변

0

이것은 분명히 학교 프로젝트입니다. 당신이 배우기를 원한다면 나는 답을주고 싶지는 않지만 실수를 지적 할 것이므로 문제를 해결할 수 있습니다. 이 방법에서 먼저 createPool

:

//Name   : createPool 
//Description : This funtion generates an array of consecutive integers from 1 to a randomly  generated 
//    : number no greater than 100. 
//Parameters : An integer array. 
//Return  : An integer (the randomly generated number), representing the size of the array. 
public static int createPool(int[]pool) { 
    Scanner read = new Scanner(System.in); 
    Random random = new Random(); 
    int size=0; 

    size=random.nextInt(100)+1; 
    pool=new int[size]; 

    return(size); 
} // end createPool 

찾는 가깝게 배열에 저장된 값에. 방법 printPool에서

둘째 :

//Name   : printPool 
//Description : This method prints the pool of numbers to the monitor no more than 10 per line. 
//Parameters : The pool array, and the size of the pool in that order. 
//Return  : None. 
public static void printPool(int[] pool, int size) { 
    int index; 
    int count=0; 

    for(index=1; index<size; index++){ 
     System.out.print(pool[index]=index); 
     System.out.print(" "); 
     count++; 
     if(count == 10){ 
      System.out.println(); 
      count=0; 
     } // end if loop 
    } // end for loop 
} // end printPool 

당신은 풀의 값을 업데이트하고 있습니다. 이 메소드는 풀의 값만 인쇄해야합니다. createPool에서 풀의 값을 설정하고 printPool에 풀의 값을 출력해야합니다. getDivisors 방법

//Name   : getDivisors 
//Description : This funtion stores all the divisors of the user's pick into the divisor array. 
//Parameters : The pool array, the divisor array, and the user's pic, in that order. 
//Return  : The number of divisors found. 
public static int getDivisors(int[] pool, int[] divisors, int pick){ 
    int num = 0; 
    int divisor = 0; 
    int numDivisors = 0; 
    int index = 0; 

for(pool[index]=1; pool[index]<=pick; pool[index]){ 
    num = pick % pool[index]; 
    if(num == 0){ 
     divisor = num; 
     numDivisors++; 
     divisors= new int[divisor]; 
    } // end if loop 
} // end for loop 
return(numDivisors); 
} // end getDivisors 

에서 다음

이 방법으로 잘못된 것들을 많이 있습니다. 먼저 for 루프를 다시 살펴보십시오. 정말 루프가 작동해야하는 방법과 루프를 사용할 때가 가장 좋은시기를 더 배워야한다고 생각합니다. 결함이있는 for 루프에 대한 기본 지식. 논리는 제수를 계산하는 데 적합하지만이 논리와 관련된 두 가지 문제가 있습니다. 1) 새 divisordivisors 어레이에 넣는 방법에 대해 알아보십시오. 이는 for 루프를 사용하는 방법에 대한 이전 호와 관련이 있습니다. for 루프 문제를 해결하면 더 명확해질 것입니다. 2) num == 0이면 거짓 일 때 divisors 어레이에 저장해야하는 것은 무엇입니까? 이 사건을 처리해야합니다, 그렇죠? printDivisors 방법 위에 지금

는 :

//Name   : printDivisors 
//Description : This method prints the contents of the divisors array to the monitor all on one line with 
//    : a leading label. 
//Parameters : The divisor array, an integer representing the number of divisors. and the  user's pick 
//    : in that order. 
//Return  : None. 
public static void printDivisors(int[] divisors, int size, int pick){ 
    int index = 0; 

    System.out.println("The divisors of " + pick + ": " + divisors[index] + " "); 
} // end printDivisors 

다시 한번, 당신은 정말 루프를 사용할 때와 때 아닌 이해할 필요가있다. 이 방법은 모두의 값을 divisors 배열에 인쇄해야합니다. 현재이 메서드는 divisors 배열 (인덱스 0의 첫 번째 값)에 하나의 값만 출력합니다.주() 함수의 마지막

:

public static void main (String[] args){ 
     Scanner read = new Scanner(System.in);    
     int  []pool = new int[100]; 
     int  []divisors = new int[100]; 
     int  size; 
     int  pick; 
     int  divisor; 

     // Program Heading 
    printProgramHeading(); 

     // Input and test 
    size = createPool(pool); 
    printPool(pool, size); 

    System.out.println(); 
    System.out.println(); 
    System.out.println("Enter a non-prime value listed in the pool above: "); 
    pick=read.nextInt(); 

     // Data Processing 
    divisor = getDivisors(pool, divisors, pick); 

     // Output Section 
    printDivisors(divisors, size, pick);  

    } // end main 

[]는 풀을 int로해야하고, []는 제수 (100)의 임의의 크기로 초기화 될 초기 값 int? 이러한 난수는 대개 "마법 수"라고합니다. 매직 번호는 설명이있는 상수로 설정하거나 프로그램에서 가져와야합니다. 다음으로 헤더를 인쇄합니다. 이것은 괜찮아 보인다. 그런 다음 풀을 만들고 풀 크기를 size에 저장하고 지정된 size을 풀로 풀을 인쇄합니다. 이것은 모두 괜찮아 보입니다. 다음으로 사용자에게 제수 입력을 폴링하고 사용자 입력으로 getDivisors 함수를 호출합니다. 또한 출력을 제수 배열의 크기를 나타내는 변수 divisor에 저장합니다. 이제 printDivisors에 당신이 전달하는 매개 변수를 보면, 뭔가이 내가 당신의 코드를 볼 수있는 모든 문제입니다

... 여기 비린내 냄새가 난다. 이렇게하면 실수를 개선하는 방법에 대한 많은 정보를 얻을 수 있습니다. 더 이상 질문이 있으시면 언제든지 물어보십시오.

0

죄송합니다. 질문에 대한 답변을 드릴 수 없습니다. 배열 대신 컬렉션을 사용하면 괜찮습니까?

import java.util.ArrayList; 
import java.util.List; 
import java.util.Scanner; 

public class GetDivisorsRefactored { 

    private static Integer[] pool; 
    private static Scanner read; 


    public static void main(String[] args) { 
     // Program Heading 
     printProgramHeading(); 
     initPool(); 
     System.out.println("Available list: "); 
     printArray(pool); 

     read = new Scanner(System.in); 
     System.out.println(); 
     System.out.println(); 
     System.out.println("Enter a non-prime value listed in the pool above: "); 
     int pick=read.nextInt();   
     Integer[] divisors = findDivisors(pick);; 
     printArray(divisors); 
    } 

    private static void printArray(Integer[] someArray) { 
     int nextRow = 0; 
     for (int num: someArray){   
       System.out.printf("%4d,", num); 
       if (++nextRow > 9){ 
        System.out.println(); 
        nextRow =0; 
       } 
     } 

    } 

    private static Integer[] findDivisors(int pick) { 
     List<Integer> divisors = new ArrayList<Integer>(); 
     for (int index = 1; index < pool.length; index++){ 
      if ((pick % pool[index]) == 0){ 
       divisors.add(pool[index]); 
      } 
     } 
     return divisors.toArray(new Integer[divisors.size()]); 
    } 

    private static void initPool() { 
     int size = (int) (Math.random()*100) + 1; 
     pool = new Integer[size]; 
     for (int index = 0; index < pool.length; index++){ 
      pool[index] = index;    
     } 

    } 

    // Function and Method Specifications 
    // Name : printProgramHeading 
    // Description : This method prints the program heading to the monitor in 
    // all caps and with a dividing line 
    // : followed by a blank line. 
    // Parameters : None. 
    // Return : None. 
    public static void printProgramHeading() { 
     System.out.println("\tGET DIVISORS"); 
     System.out.println(" ************************"); 
     System.out.println(); 
    } // end printHeading 

}