我需要创建一个数组。长度必须使用JOptionPane设置。另外,我还必须用随机数填充数组。这就是我走了多远。

import javax.swing.*;
import java.util.Arrays;
import java.util.Random;

public class Aufgabe2
{
    public String a;

    public static void main(String[] args)
    {
        String a = JOptionPane.showInputDialog("How big should the array be?");
        try
        {
            Integer.parseInt(a);
            int meinArray[];
            meinArray = new int[a];
            Random rand = new Random();

            for (int i = 0; i < a; i++)
            {
                meinArray[i] = rand.nextInt();
            }
            System.out.println(Arrays.toString(meinArray));
        }

        catch (NumberFormatException e)
        {
            System.out.println(a + " isn`t a valide input. Please insert a number");
        }

    }
}

最佳答案

您需要将Integer.parseInt(a)的结果存储到某个变量中,然后使用它,例如

int x= Integer.parseInt(a);
int meinArray[];
meinArray = new int[x];
Random rand = new Random();

for (int i = 0; i < x; i++){
    meinArray[i] = rand.nextInt();
}

10-07 16:09