用Java反向输出数组的内容

时间:2019-04-12 06:14:42

标签: java arrays

我的任务是创建一个大小为20的数组。询问用户他/她想输入多少个数字。将所有这些数字放在一个数组中,然后反向输出该数组。我已经完成了“反向输出该数组”部分。

import java.util.Scanner;

public class Activity7 {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System. in );
        System.out.println("How many numbers?");
        int quantityOfNumbers = keyboard.nextInt();

        int[] numbers = new int[20]; //making an array the size of 20
        //0 - 19 (Valid values of the array)
        for (int subscript = 0; subscript < quantityOfNumbers; subscript++) {
            System.out.println("Enter number " + subscript);
            numbers[subscript] = keyboard.nextInt();
        }
        System.out.println("Array Contents");
        for (int subscript = 19; subscript >= 0; subscript--) {
        }
    }
}

2 个答案:

答案 0 :(得分:0)

如果要打印不包含空元素的数组,则可以使用类似的方法。由于0是默认的int值,因此只要不为0,就将其打印出来。

public static void reverse(int[] array)
    {
        for(int i=array.length-1;i>=0;i--)
        {
            if(array[i]!=0)
            {
                System.out.println(array[i]);
            }
        }
    }

答案 1 :(得分:-2)

我不确定您要寻找什么。您能指定更多吗?无论如何,我正在完成您的代码以匹配提供的输出:

import java.util.Scanner;

public class Activity7
{
  public static void main(String[] args)
  {
    Scanner keyboard = new Scanner(System.in);
    System.out.println("How many numbers?");
    int quantityOfNumbers = keyboard.nextInt();

    int[] numbers = new int[20]; //making an array the size of 20

    //0 - 19 (Valid values of the array)
    for (int subscript = 0; subscript < quantityOfNumbers; subscript++)
    {
      System.out.println("Enter number " + subscript);
      numbers[subscript] = keyboard.nextInt();
    }
    System.out.println("Array Contents");
    for (int subscript = 19; subscript >= 0; subscript--)
    {
      if (subscript >= quantityOfNumbers) System.out.println("Subscript " + subscript + "is empty");
      else System.out.println("Subscript " + subscript + "contains " + numbers[subscript]);
    }
  }
}