函数/方法和数组

时间:2014-12-03 05:18:37

标签: java arrays function methods

我的班级刚开始学习如何用函数和方法编写代码,这是我第一次尝试 - 我觉得我只是在混淆自己。

分配是为随机选择的数字创建一个数字池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  

谢谢!

2 个答案:

答案 0 :(得分: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)重新考虑如何将新的divisor放入divisors数组中。这与您之前使用for循环的问题有关。一旦你解决了for循环问题,这应该变得更加明确2)当divisors false 时,你应该在num == 0数组中存储什么?你需要处理这个案子,对吧?

现在进入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

再一次,你真的需要了解何时何地 - 不要使用for循环。此方法应打印出divisors数组中所有值。目前,此方法仅在divisors数组中打印出一个值(第一个值,在索引0处)。

最后,在main()函数中:

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 [] pool和int []除数最初是否应该以100的任意大小初始化?像这样的随机数通常被称为&#34;魔数&#34;。幻数应该被设置为具有描述的常量,或者从程序中取出。接下来,打印标题。这似乎没问题。然后创建池,并将池大小保存到size,并打印具有传递给函数的给定size的池。这一切似乎都很好。接下来,您将轮询用户以获取除数输入,并使用用户输入调用getDivisors函数。您还将输出保存到变量divisor中,该变量表示除数数组的大小。 现在,看看你传递给printDivisors 的参数,这里有点腥味......

这些是我在您的代码中看到的所有问题。这应该为您提供有关如何改善错误的大量信息。如果您有任何疑问,请随时提出。

答案 1 :(得分:0)

抱歉,我无法评论您的问题。如果使用Collections而不是数组,这样可以吗?

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

}