如何使用JOptionPane设置数组的长度

问题描述 投票:0回答:2

我需要创建一个数组。长度必须使用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");
        }

    }
}
java swing joptionpane
2个回答
0
投票

您缺少解析的整数分配

        int size=Integer.parseInt(a);//you are missing int size= here

        int[] meinArray = new int[size];
        Random rand = new Random();

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

            System.out.println(Arrays.toString(meinArray));

0
投票

您需要将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();
}
© www.soinside.com 2019 - 2024. All rights reserved.