[英]How to store user input into an existing Array?
I have an array of: 我有一个数组:
String names[] = {"John"};
int id[] = {"1"};
and I have a code that ask for a user input: 我有一个代码要求用户输入:
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?
You should use a List<String>
and List<Integer>
respectively instead of arrays, as with the latter you cannot change the size once initialised. 您应该分别使用List<String>
和List<Integer>
而不是数组,因为后者一旦初始化就无法更改大小。
Example: 例:
List<String> names = new ArrayList<>(Collections.singletonList("John"));
List<Integer> ids = new ArrayList<>(Collections.singletonList(1));
then add: 然后加:
names.add(newName);
ids.add(newId);
Alternatively, you should consider using a Map<String, Integer>
or vice versa. 另外,您应该考虑使用Map<String, Integer>
,反之亦然。
Try this 尝试这个
Map<Integer,String> map=new HashMap<Integer,String>();
map.put(newId,newName);
I java arrays are immutable, meaning you can't change the value once set. 我的Java数组是不可变的,这意味着一旦设置就无法更改该值。 I have built a function that can acieve what you want: 我建立了一个可以满足您想要的功能:
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);
Array size are fixed once initialized. 数组大小一旦初始化就固定。 And, in your case you need dynamic array so you can implement your own Dynamic array or there is a library for Dynamic array ie List. 并且,在您的情况下,您需要动态数组,以便可以实现自己的动态数组,或者有一个用于动态数组的库,即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.