I am trying to get user input in a 2D array. I would like not to use java.util.Arrays
if possible.
User input looks like this, the first integer being the number, the second the index of the integer.
3 3
1 2
3 2
This is what I get
[3,3,1][2,3,2][][][][]
This is what I would like to get
[][1,3][3][][][]
int x = sc.nextInt();
int array[][] = new int[6][x];
for (int i = 0; i < x; i++ ){
for (int j = 0; j < x; j++) {
array[i][j] = sc.nextInt();
}
}
System.out.println(Arrays.deepToString(array));
I expect you mean format:
number index_to_add
This is not simple, because you don't know, how many numbers will be in array at start.
I would use a collection like ArrayList
etc.
If you really want to use just arrays, you have to have a top limit.
ArrayList version:
ArrayList<Integer>[] list = new ArrayList<Integer>[6];
//init
for(int i=0;i<list.length;i++){
list[i] = new ArrayList<Integer>();
}
//fill
while(sc.hasNextInt()){
int number = sc.nextInt();
if(sc.hasNextInt()){
int index_to_add = sc.nextInt();
list[index_to_add].add(number);
}else{
break;
}
}
Note: code not tested;
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.