通过用户给出两个数字来创建一个数组并在Java中打印该数组

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

我想给用户提供两个数字并创建一个数组。然后打印数组。我应该如何在java中完成这个任务?

这是我的代码。我给出了数字 5 和 25。但是它不能正常工作。

我想要的输出:

[6,7,....,23,24]

带有输入的系统输出最小值:5最大值:25

[0, 0, 0, 0, 0][0, 0, 0, 0, 0, 0][0, 0, 0, 0, 0, 0, 0][0, 0, 0, 0, 0, 0, 0, 0][0, 0, 0, 0, 0, 0, 0, 0, 0][0, 0, 0, 0, 0, 0, 0, 0, 0, 0][0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0][0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0][0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0][0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0][0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0][0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0][0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0][0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0][0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0][0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0][0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0][0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0][0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0][0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

我的代码:

import java.util.Arrays;
import java.util.Scanner;

public class JavaApplication18 {

    public static void main(String[] args) {
        Scanner reader = new Scanner (System.in);
        System.out.print("min value: ");
        int min = reader.nextInt();

        // Ask the user to input the minimum value
        System.out.print("max value: ");
        int max = reader.nextInt();
    
        for (int a = min; a < max; a++) {
            int [] userArray = new int[a]; 
            System.out.print(Arrays.toString(userArray));
        }
    }
}

我想要的值 5 和 25 的输出:

[6,7,...,23,24]

java arrays printing range user-input
1个回答
0
投票

首先,您不是在每次迭代中创建一个数组,而是在

int [] userArray = new int[a];
循环内使用
for
行创建一个数组。这解释了您不需要的系统输出,它显示了多个数组......

您必须在循环外部创建具有正确大小的数组,然后将其填充到内部计算正确的索引和值。

这是一个示例方法/函数:

public static void printArray(int min, int max) {
    // create an array with the correct amount of numbers
    // which is the difference of max and min
    int[] array = new int[max - min];
    // iterate from minimum to maximum (exclusively)
    for (int i = min; i < max; i++) {
        // and put the number at indexes staring by 0
        array[i - min] = i;
    }
    // print the array
    System.out.println(Arrays.toString(array));
}

使用示例值在

main(…)
中调用它,例如

public static void main(String[] args) {
    printArray(5, 25);
}

将产生以下(所需的)输出:

[5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
© www.soinside.com 2019 - 2024. All rights reserved.