如何编辑具有预定义值的数组以还包括用户输入 JAVA

How to edit an array with predefined values to also include user input JAVA

我有一个数组 (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 我们有 Collections。对于您想要查看列表的示例,特别是 ArrayList 或 Vector。

https://docs.oracle.com/javase/tutorial/collections/interfaces/list.html

我建议您考虑使用列表,主要是 ArrayList 来实现此功能,但如果您真的想使用数组,那么您总是可以使用 System.arraycopy() 方法来完成复制。例如:

public static String[] combine(String[] first, String[] second) {
    String[] copy = Arrays.copyOf(first, first.length + second.length);
    System.arraycopy(second, 0, copy, first.length, second.length);
    return copy;
}

此方法创建第一个输入字符串的副本,然后将第二个字符串的内容添加到其中,然后 returns。只需在 FruitBowl 数组上调用此方法即可复制其内容:

FruitBowl = combine(FruitBowl, FruitName);