繁体   English   中英

如何使用预定义值编辑数组以包含用户输入的JAVA

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

我有一个数组(FruitBowl),我希望每次用户输入信息EG时都可以更新它。如果用户要添加水果木瓜,我希望将其添加到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;
}

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

FruitBowl = combine(FruitBowl, FruitName);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM