[英]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.