简体   繁体   English

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

[英]How can I fix my code? 2D Array

I want to create a 2D array using the user's input and the creating random numbers in the second line. 我想使用用户的输入创建一个2D数组,并在第二行创建随机数。 Eg: 例如:

Output should be: 输出应该是:

If the user enters "7" then: 如果用户输入“7”,则:

1 2 3 4 5 6 7 (User's input) 1 2 3 4 5 6 7(用户输入)

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

but instead I only get one random number. 但相反,我只得到一个随机数。

My code is working but I can't see to create the array correctly. 我的代码正在运行,但我看不到正确创建数组。 My code: 我的代码:

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;
    }
}

How can I fix it? 我该如何解决?

Would this help? 这会有帮助吗?

    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);
    }

Am not too certain about what you mean by: 我不太确定你的意思是:
1 2 3 4 5 6 7 (User's input) 1 2 3 4 5 6 7(用户输入)
0 2 4 8 9 8 5 (Random numbers) 0 2 4 8 9 8 5(随机数)
Do you want users to manually enter "1 2 3 4 5 6 7"? 您是否希望用户手动输入“1 2 3 4 5 6 7”?

Eitherway, here's something to help with the printing aspect: 无论如何,这里有一些帮助打印方面:

    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());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM