简体   繁体   中英

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.

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.

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. 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<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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM