I have a question: I want an array that I want to copy over to another array so that when the user inputs something in the first array and wants to add more items (in another array) it doesn't completely erase what the user had originally.
Here's my code:
System.out.println("Input up to '10' numbers for current array: ");
int[] array1;
array1 = new int[10];
Scanner scan = new Scanner(System.in);
for (int i = 0; i < 10; i++) {
System.out.println((i+1)+": ");
int input = scan.nextInt();
if (input == 0) {
break;
} else {
array1[i] = input;
}
int[][] array2 = new int[2][];
for (i = 0; i <3; i ++){
array2[i] = Arrays.copyOf(array1[i], array1[i]);
}
}
}
}
EDIT: The second part I'm trying to loop the first array into the second array.
I understand that your problem is save the input in a first array with a maximum, but with the possibility to quit if you put zero. Then copy the data from array1 into an array2 with the size of the data inserted. Is it correct?
Well, I modified your code to show you the use of the instruction Arrays.copyOf (you need to import java.util.Arrays). The point is, that you need to write the copy instruction out of the for loop. I recommend you to use the length property instead the plain number in the range of the for loop. Also, if you want to copy the entire array1 including zeros into array2, replace the second parameter:
array2 = Arrays.copyOf(array1, array1.length);
This is the code:
public static void main(String[] args) {
System.out.println("Input up to '10' numbers for current array: ");
//Declaring array1 and scanner
int[] array1 = new int[10];
int i;
Scanner scan = new Scanner(System.in);
//Your loop to ask for data into array1
for (i = 0; i < array1.length; i++) {
System.out.print((i+1)+": ");
int input = scan.nextInt();
if (input == 0) {
break;
} else {
array1[i] = input;
}
}
//Copy array1 into array2
int[] array2 = new int[i];
for(int j=0; j<i;j++){
array2[j] = array1[j];
}
//array2 = Arrays.copyOf(array1, i);
// array2 = copy(array1, i);
//Print out the second array, only for test
for (int j = 0; j < array2.length; j++) {
System.out.println(array2[j]);
}
scan.close();
}
public static int[] copy(int [] source, int len){
int [] target = new int[len];
for(int i=0; i<len;i++){
target[i] = source[i];
}
return(target);
}