简体   繁体   English

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

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

I have an array (FruitBowl) and I'd like it to be updated every time the user inputs information EG If the user wants to add the fruit papaya I'd like it to be added to the FruitBowl 我有一个数组(FruitBowl),我希望每次用户输入信息EG时都可以更新它。如果用户要添加水果木瓜,我希望将其添加到FruitBowl中

I know how I'd do it if it was just going to be saved to array FruitName (as shown below) but not FruitBowl (with it's predefined values) 我知道如果将其保存到FruitName数组(如下所示)而不是FruitBowl(具有预定义值)的情况下该怎么做

Please help! 请帮忙!

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();

            }

}

} }

Primitive arrays like your FruitBowl are static in length, they cannot have elements added to them. FruitBowl这样的原始数组的长度是静态的,不能向其中添加元素。 In order to add a value to the primitive array, you will need to instantiate a new one that is longer, copy the values of the previous array, and then set the new value. 为了向原始数组添加一个值,您将需要实例化一个更长的新数组,复制先前数组的值,然后设置新值。 Luckily in Java we have Collections. 幸运的是,在Java中,我们有Collections。 For your sample you want to look into Lists, specifically an ArrayList or Vector. 对于您的样本,您想查看列表,特别是ArrayList或Vector。

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

I would recommend that you look into using Lists, primarily an ArrayList for this functionality, but if you really want to use arrays then you could always just use the System.arraycopy() method to do the coppying. 我建议您考虑使用列表,主要是使用ArrayList来实现此功能,但是如果您真的想使用数组,则可以始终使用System.arraycopy()方法进行调整。 Ex: 例如:

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;
}

This method creates a copy of the first input String, then adds the contents of the second String to it and returns that. 此方法创建第一个输入String的副本,然后将第二个String的内容添加到其中并返回。 Just call this method on your FruitBowl array to copy its contents: 只需在FruitBowl数组上调用此方法即可复制其内容:

FruitBowl = combine(FruitBowl, FruitName);

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

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