首页 > 解决方案 > 如何根据用户输入打印多个整数数组?

问题描述

我正在创建一个 java 程序,它提示用户输入数组中的项目数(非负整数),读取它,并将其保存在一个 int 变量中。然后它提示用户输入所有项目的值并将它们保存在一个 int 数组中。之后,程序以 [x1, x2, ... ,xn] 的形式打印数组的内容。不需要用户验证。该程序应该可以正常运行,但是,当我尝试为用户输入多个输入时,输出出现了问题。

而不是显示这个:

Enter the number of items: 2
Enter the value of all items (separated by space): 88
Enter the value of all items (separated by space): 99
The values are: [88, 99]

输出变成这样:

Enter the number of items: 2
Enter the value of all items (separated by space) : 88
Enter the value of all items (separated by space) : 99
The values are: [88]
The values are: [99]

另外,当我输入 0 作为项目数时,输出应该显示这个

Enter the number of items: 0
The values are: []

但我的输出显示了这一点:

Enter the number of items: 0

当项目数为0时,它甚至不显示值的括号。下面附上我的编码:

import java.util.Scanner;


public class PrintArray{



public static void main(String[] args) {
 // Declare variables
      int numItems;
      int[] items;  // Declare array name, to be allocated after numItems is known


  // Prompt for a non-negative integer for the number of items;
  // and read the input as "int". No input validation.
  Scanner in = new Scanner(System.in);
  System.out.print("Enter the number of items: ");
  numItems = in.nextInt();


  // Allocate the array
  items = new int[numItems];

  // Prompt and read the items into the "int" array, if array length > 0
  if (items.length > 0) {

     for (int i = 0; i < items.length; ++i) {
        System.out.print("Enter the value of all items (separated by space) : ");
        items[i] = in.nextInt();

     }
  }

  // Print array contents, need to handle first item and subsequent items differently

  for (int i = 0; i < items.length; ++i) {
     if (i == 0) {
        // Print the first item without a leading commas
        System.out.println("The values are: [" + items[i] + "]");
     } else {
        // Print the subsequent items with a leading commas
        System.out.println("The values are: [" + items[i] + "]");
     }

  }



  }
}

如果有人可以帮助我,那就太好了。非常感谢!

标签: java

解决方案


您正在迭代同一个数组,因此它被打印了很多次。最后试试这个for

String  values = ""
for (int i = 0; i < items.length; ++i) {

    if (i == 0) {
        // Print the first item without a leading commas
        values = values + items[i];
     } else {
        // Print the subsequent items with a leading commas
        values = values + "," + items[i];
     }

System.out.println("The values are: [" + values + "]");

或者你也可以这样做,看起来更具可读性:

String  values = "" + items[0];
for (int i = 1; i < items.length; ++i) {
        // Print the subsequent items with a leading commas
        values = values + "," + items[i];
     }

System.out.println("The values are: [" + values + "]");

推荐阅读