So, the problem is a bit advanced for a beginner like myself which is why I hope you can ignore my mistakes.
We need to create a method that takes an array, a value that I want to place in the array and the index values (spaces) in the array.
Because my teacher was not concrete with what she wanted, she didn't specify if the array had to be empty or full which is what has confused me the most in this exercise.
The static method has to be named:
addAtIndex( int [] a, int value, int index)
and do the following:
If the last space in the array is 0 or empty and I want to place a new integer value in one of the already occupied spaces, I need to move every element to the right and leave that space free in order to be able to do that.
If the last space has already been taken by an integer value, I need to "resize" the array and make more space so that I can keep entering more integer values. I know that you cannot resize an array and even less keep all the elements intact so I need to create a larger array to do that.
I have been programming in Java less than two months so I find this quite difficult.
I have been able to create an empty array, and I have entered different numerical values in the array with the given parameters. All of this has been done in public static void main and not in a method. I can't seem to be able to do this in a method, especially I have no idea how I can move everything in an array to the right.
import java.util.Arrays;
import java.util.Scanner;
public class Array{
public static void main (String args []){
Scanner input = new Scanner(System.in);
int [] array = new int[10];
for (int x = 0; x <= 9; x++){
int index = input.nextInt();
int value = (int)(Math.random()*50);
//move elements below insertion point.
for (int i = array.length-1; i > index; i--){
array[i] = array[i-1];
}
//insert new value
array[index] = value;
}
System.out.println(Arrays.toString(array));
}
}
This of course is way off from what the teacher wants me to do. What I'm doing here is just creating an array, entering random integers in the indexes that I choose and printing it out. I need some help.