我该如何修复我的代码? 2D阵列

时间:2015-09-22 22:05:51

标签: java arrays

我想使用用户的输入创建一个2D数组,并在第二行创建随机数。 E.g:

输出应为:

如果用户输入“7”,则:

  

1 2 3 4 5 6 7(用户输入)

     

0 2 4 8 9 8 5(随机数)

但我只得到一个随机数。

我的代码正在运行,但我看不到正确创建数组。 我的代码:

import java.util.Scanner;


public class Main {


    public static void main(String[] args) {



        Scanner input = new Scanner(System.in);
        System.out.print("Enter number of exits: ");
        int n = input.nextInt();

        int [][] A = new int[2][n];
        for(int i=0; i<A.length; i++){
            for (int j = 0; j<n; j++) {
                  A[i][j] = (int) (Math.random()*10);
            }
        }

        System.out.println(A[1][n-1]);
        System.out.print("Distance between exit i and exit j is: " + distance());
    }



    public static int distance(){
        Scanner input = new Scanner(System.in);

        System.out.print("Please enter exit i: ");
        int i = input.nextInt();
        System.out.print("Please enter exit j: ");
        int j = input.nextInt();
        return i + j;
    }
}

我该如何解决?

2 个答案:

答案 0 :(得分:3)

这会有帮助吗?

    int n = input.nextInt();
    Random rand = new Random();
    int [][] A = new int[2][n];
    for (int i = 0; i<n; i++) {
       A[0][i] = i+1;
       A[1][i] = rand.nextInt(10);
    }

答案 1 :(得分:0)

我不太确定你的意思:
    1 2 3 4 5 6 7(用户输入)
    0 2 4 8 9 8 5(随机数)
您是否希望用户手动输入“1 2 3 4 5 6 7”?

无论如何,这是帮助打印方面的东西:

    public static void main(String[] args) {
    // TODO code application logic here
     Scanner input = new Scanner(System.in);
    System.out.print("Enter number of exits: ");
    int n = input.nextInt();

    int [][] A = new int[2][n];
    for(int i=0; i<A.length; i++){
        for (int j = 0; j<n; j++) {
              A[i][j] = (int) (Math.random()*10);
        }
    }

    for(int[] b: A)
    {
        for(int k: b)
        {
            System.out.print(k + " ");       
        }
        System.out.println();
    }
    System.out.print("Distance between exit i and exit j is: " + distance());
}
相关问题