java使用扫描器为用户输入设置数组大小

nle07wnf  于 2021-08-20  发布在  Java
关注(0)|答案(2)|浏览(256)

我想让用户能够在我的程序中选择int数组的大小
现在我有以下代码:

public class SortTests {
    private static int size;
    private static int [] myArray = new int [size]; 

    public static void setArraySize() {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter a whole number to specify the size of the array: ");
        size = scan.nextInt();

    }

    public static void fillArray() {
        Random randNum = new Random();
        for (int i = 0; i < myArray.length; i++) {
            myArray[i] = randNum.nextInt(100);
        }
    }

我不知道为什么,但当我去测试并打印我的数组时。tostring只会打印“'[]”(显然它没有做它应该做的事情并填充int数组)。
有没有人对我如何整理我的代码并使其真正起作用有什么建议?

yduiuuwa

yduiuuwa1#

您已经创建了数组,并且setarraysize仅更改大小变量。

public class SortTests {
    private static int size; <-- setArraySize affects this.
    private static int [] myArray = new int [size];  <-- setArraySize does not affect this.  Size was defaulted to 0, so myArray will always be a 0-sized array.

更改为类似以下内容:

public class SortTests {
    private static int [] myArray = new int [size]; 

    public static void setArraySize() {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter a whole number to specify the size of the array: ");
        int size = scan.nextInt();
        myArray = Arrays.copyOf(myArray, size);
    }
lf5gs5x2

lf5gs5x22#

补充@john的答案
这不是初始化数组的正确方法。您使用的是空引用 size 初始化 myArray . 初始化 myArray 在类示例化时发生。这意味着 size 在创建类时读取一次,然后丢弃。因此,您提供的代码中的初始数组大小始终是 size . 自从 size 如果为null,则数组应为空。
如果要检索特定大小的数组,需要在用户提交输入后动态创建它(根据@john的回答)
另外,您肯定会考虑使用java的集合框架来代替原始数组。数组大小是动态管理的。

package com.company;

import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;

public class ScannerToArraySize {

    private static Integer size;
    private static ArrayList<Integer> myArray = new ArrayList<>();

    public static void setArraySize() {
        Scanner  scan = new Scanner(System.in);
        System.out.println("Enter a whole number to specify the size of the array: ");
        size = scan.nextInt();
    }

    public static void fillArray() {
        Random randNum = new Random();
        for (int i = 0; i < size; i++) {
            myArray.add(randNum.nextInt(100));
        }
    }

    public static void printArray(){
        for (Integer integer : myArray) {
            System.out.println(integer);
        }
    }
}

相关问题