我有一个数组(FruitBowl),我希望每次用户输入信息时都会更新它 例如。 如果用户想要添加水果木瓜,我希望将其添加到 FruitBowl
如果只是将其保存到数组 FruitName (如下所示)而不是 FruitBowl (具有预定义值),我知道该怎么做
请帮忙!
import java.util.Scanner;
public class FruitArrayEdit
{
public static void main(String[]args)
{
Scanner input = new Scanner(System.in);
String [] FruitBowl = {"(Plums)", "(Oranges)", "(Mangos)", "(Strawberries)"};
System.out.println("How many types of fruit would you like to add to the database?");
int FruitNum = input.nextInt();
String[] FruitName = new String[FruitNum];
for (int count = 0; count < FruitName.length; count++)
{
System.out.println("Enter the name of the fruit " +(count+1));
FruitName[count] = input.next();
}
}
}
最佳答案
像 FruitBowl
这样的原始数组的长度是静态的,不能向其中添加元素。为了向原始数组添加值,您需要实例化一个更长的新数组,复制前一个数组的值,然后设置新值。幸运的是,在 Java 中我们有集合。对于您的示例,您需要查看列表,特别是 ArrayList 或 Vector。
https://docs.oracle.com/javase/tutorial/collections/interfaces/list.html
关于java - 如何编辑具有预定义值的数组以包含用户输入 JAVA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29584992/