提示输入的数组大小 [英] Prompt for Array Size For Input

查看:133
本文介绍了提示输入的数组大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程序按照我的意愿执行,但是我希望修改扫描程序,以便用户可以指定他们输入的数组的长度。因此,当程序启动时,它会询问多少个数字。然后它将按顺序执行打印数字,然后按相反顺序打印。这是我目前的计划。我需要修改什么来允许这个?

My program executes as I desire it to, however I wish to modify the scanner such that the user can specify the length of the array they are inputting. So when the program launches it will ask how many numbers. Then it will follow through with its execution of printing the numbers in order and then in reverse order. Here is my current program. What would I need to modify to allow this?

import java.util.Scanner;

public class Assignment01b {

    public static void main (String[] args) {

        int[] numbers=new int[6];
        Scanner sc=new Scanner(System.in);
        System.out.println("Please enter elements...");
        for(int j=0;j<6;j++)
            numbers[j]=sc.nextInt();

         if (printOriginalArray(numbers) != 0)
             System.out.println("ERROR!");

         if (printInReverse(numbers) != 0)
             System.out.println("ERROR!");

         System.out.println("\nProgram completed successfully!");

    }

    public static int printOriginalArray(int[] list) {

        System.out.println("The list in order is: ");

         for (int num: list)
         System.out.print(num + " ");

         return 0;

    }

    public static int printInReverse(int[] list) {

        System.out.println("\nThe list in reverse order is:");

        for (int i = list.length-1; i >= 0; i--) {
            System.out.print(list[i] + " ");
        }

        return 0;

    }

}


推荐答案

使用此Follow代码段

use this Follow code snippet

Scanner sc = new Scanner(System.in);
int[] numbers = new int[sc.nextInt()];

这篇关于提示输入的数组大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆