没有打印随机2d数组

时间:2016-06-08 13:30:01

标签: java arrays loops for-loop random

public class Alfabhto {

int[][] pinakas = new int[3][6];
String[] gramata ={"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};

public static void main(String[] args) {
    Scanner s = new Scanner(System.in);
    System.out.println("Enter an alphanumeric combination");
    String fail = s.nextLine();

    System.out.println(pinakas[i][j]);

}

    public int[][] Numbers() {

    Random rand = new Random();
    for (int i=0;i<3;i++)
    {
        for (int j=0;j<6;j++)
        {
            pinakas[i][j] = rand.nextInt(38)-12;
        }
    }
    return pinakas;

}
}

首先,我是java的新手。主要功能正常工作,并要求用户提供输入。这里没有使用一些元素(比如gramata数组),所以忽略它们。

问题是:方法编号应该用随机数填充pinakas数组然后打印它们。如果它在方法中,它什么都不做。外面它会带来错误,因为它无法获得“pinakas”数组或i和j。有任何想法吗?

2 个答案:

答案 0 :(得分:3)

该代码存在几个问题,请参阅注释:

// Need to import Random
import java.util.Random;

public class Alfabhto {

    String[] gramata ={"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
    // This neesd to be final for Numbers to access it
    final int[][] pinakas = new int[3][6];

    // There's no reason for Numbers to be public, or to extend Alfabhto, or in
    // fact to be a class at all. Recommend making it a static method within
    // Alfabhto (in which case gramata and pinakas must also be static), or an
    // instance method if appropriate (in which case pinaka does not need to be
    // final anymore, though you might leave it that way if you never
    // intend to replace the array with a different one.
    // Also recommend making that method (static or instance) a  private method.
    public class Numbers extends Alfabhto {
        public Numbers() {
            // Create this once and reuse it
            Random rand = new Random();

            // Note using <, not <=, on the loops
            for (int i = 0; i < 3; i++) {
                for (int j = 0; j < 6; j++) {
                    pinakas[i][j] = rand.nextInt(38) - 12;
                    System.out.println(pinakas[i][j]);
                }
            }
        }
    }

    // Since Numbers is an inner class, we need to be able to create instances of Alfabhto
    private Alfabhto() {
    }

    // We need something in Alfabhto to run the Numbers constructor    
    private void run() {
        // Run the code in the Numbers constructor
        new Numbers();
    }

    public static void main(String[] args) {
        /* None of this does anything, presumably you'll use it later...
        Scanner s = new Scanner(System.in);
        System.out.println("Enter an alphanumeric combination");
        String fail = s.nextLine();
        */
        // Run our run method, which will run the code in the Numbers constructor
        new Alfabhto().run();
    }
}

答案 1 :(得分:-1)

在你的main函数中,你永远不会创建一个Numbers实例,所以无论你在那里写的是什么都没有被调用。一旦你创建了一个新的Numbers(),它就应该打印出来。