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