簡體   English   中英

如何將用戶輸入存儲到現有陣列中?

[英]How to store user input into an existing Array?

我有一個數組:

String names[] = {"John"};
int id[] = {"1"};

我有一個代碼要求用戶輸入:

Scanner kbd = new Scanner(System.in);
System.out.println("Input new name: ");
String newName = kbd.nextLine();
//How do i do this part? Add the newName to the variable name without deleting the old contents?
System.out.println("Input id for " +newName);
Int newId = kbd.nextInt();
//This part aswell how do i add the newId to the variable id?

您應該分別使用List<String>List<Integer>而不是數組,因為后者一旦初始化就無法更改大小。

例:

List<String> names = new ArrayList<>(Collections.singletonList("John"));
List<Integer> ids = new ArrayList<>(Collections.singletonList(1));

然后加:

names.add(newName);
ids.add(newId);

另外,您應該考慮使用Map<String, Integer> ,反之亦然。

嘗試這個

Map<Integer,String> map=new HashMap<Integer,String>();  
      map.put(newId,newName);

我的Java數組是不可變的,這意味着一旦設置就無法更改該值。 我建立了一個可以滿足您想要的功能:

public static int[] appendToArray(int[] array, int value) {
     int[] result = Arrays.copyOf(array, array.length + 1);
     result[result.length - 1] = value;
     return result;
}
//--------------------------------------------
Int newId = kbd.nextInt();
id[] = appendToArray(id, newId);

數組大小一旦初始化就固定。 並且,在您的情況下,您需要動態數組,以便可以實現自己的動態數組,或者有一個用於動態數組的庫,即List。

List<String> names = new ArrayList<>();
List<Integer> id = new ArrayList<>(Collections.singletonList(1));
names.add("John");
id.add(1);
//Your code
names.add(newName);
id.add(newId);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM