gpt4 book ai didi

java - 如何根据用户输入打印多个整数数组?

转载 作者:行者123 更新时间:2023-12-01 18:22:24 25 4
gpt4 key购买 nike

我正在创建一个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] + "]");
}

}



}
}

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

最佳答案

在循环中,您将打印整个句子,而您可以将数组元素附加到字符串中,以便稍后打印。第二个问题是因为数组为空,这使得第一次迭代本身的循环条件为假。因此循环体不会被执行。

您可以尝试如下所示的操作。

String output = "[";
for (int i = 0; i < items.length; ++i) {
output += items[i] + ", ";
}

// remove last comma and space
output = output.substring(0, output.length() - 2);
output += "]";
System.out.println("The values are: " + output);

关于java - 如何根据用户输入打印多个整数数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60282139/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com