简体   繁体   中英

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

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)

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. 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. For your sample you want to look into Lists, specifically an ArrayList or Vector.

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. 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. Just call this method on your FruitBowl array to copy its contents:

FruitBowl = combine(FruitBowl, FruitName);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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