我的程序按照我的意愿执行,但我希望修改扫描程序,以便用户可以指定他们输入的数组的长度。因此,当程序启动时,它会询问有多少个数字。然后它将按顺序执行打印数字,然后按相反顺序打印。这是我目前的计划。我需要修改什么来允许这个?
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;
}
}
答案 0 :(得分:1)
使用此关注代码段
Scanner sc = new Scanner(System.in);
int[] numbers = new int[sc.nextInt()];
答案 1 :(得分:0)
您只需要进行以下更改。
public static void main (String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Please enter no of elements...");
int noOfElements = sc.nextInt();
int[] numbers=new int[noOfElements];
System.out.println("Please enter elements...");
for(int j=0;j<noOfElements;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!");
}