我有一个数组:
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?
答案 0 :(得分:0)
您应该分别使用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>
,反之亦然。
答案 1 :(得分:0)
试试这个
Map<Integer,String> map=new HashMap<Integer,String>();
map.put(newId,newName);
答案 2 :(得分:0)
我的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);
答案 3 :(得分:0)
一旦初始化,数组大小就固定了。并且,在您的情况下,您需要动态数组,以便您可以实现自己的动态数组,或者有一个动态数组库,即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);