How to insert a number into an array in java - java

Ok I am trying to do the following using an array.
Say I have one array
1 4 3 7 8
and at index 1 I want to place a 2 to get the following
1 2 4 3 7 8
How do I do this I think I have to make one array to keep everything before the index, one array to keep everything after the index.
And the add one more element to the array with everything before the index. The create a new longer array with everything before the index and everything after the index.
But I cannot seem to do it. This be what I tried.
//this program will test out how to replace an array with more stuff
public class Raton
{
public static void main(String[] args)
{
int[] gato={1,4,3,7,8};
int[] perro = new int[gato.length+1];
int[] biggie = new int[gato.length];
int index=2; //store item index 2
System.out.println("the contents of gato are ");
for(int i=0; i<gato.length;i++)
{
System.out.println(gato[i]);
}
for(int i=0;i<gato.length;i++)
{
if(i<index)
{
perro[i]=gato[i];
}
else
{
int red=0;
biggie[red]=gato[i];
red++;
}
}
//put two in the new place
for(int i=0;i<perro.length;i++)
{
System.out.println(" \n the contents of peero are " + perro[i]);
}
for(int i=0; i<biggie.length;i++)
{
System.out.println("\nthe contents of biggie are " + biggie[i]);
}
}
}

First you need to get both the new number and new index.
int newNumber = 2;
int newIndex = 1;
Create the new array with size+1 of old array
int[] gato = {1,4,3,7,8}; //old array
int[] perro = new int[gato.length+1]; //new array
Then keep track of of two counters. j for old array and i for new array.
int j = 0;
for(int i = 0; i<perro.length; i++){
if(i == newIndex){
perro[i] = newNumber;
}
else{
perro[i] = gato[j];
j++;
}
}
Here's a test run. This solution is assuming you have a constraint where you can only use arrays (not ArrayList or any other prebuilt classes in Java)

Use an ArrayList<Integer> instead of arrays, they allow easy insertion of new elements, and arraylists allow that at specific indices too.
int[] gato={1,4,3,7,8};
List<Integer> list = new ArrayList<>(Arrays.asList(gato));
list.add(1, 2);

I haven't tested this code, but something similar should do the trick.
public class Raton {
public static void main(String[] args) {
int[] originalArray = {1,4,3,7,8};
int[] modifiedArray = new int[originalArray.length + 1];
int index = 2;
for(int i = 0; i < (originalArray.length + 1); i++) {
if(i==1) {
modifiedArray[i] = index;
}
else if(i < 1){
modifiedArray[i] = originalArray[i];
}
else {
modifiedArray[i] = originalArray[i-1];
}
}
}
}

Try to look at the "before" and "after" arrays:
Before
┌─┬─┬─┬─┬─┐
│1│4│3│7│8│
└─┴─┴─┴─┴─┘
0 1 2 3 4
After
┌─┬─┬─┬─┬─┬─┐
│1│2│4│3│7│8│
└─┴─┴─┴─┴─┴─┘
0 1 2 3 4 5
One thing you already noticed is that you need a target array that is 1 bigger than the original array. That's correct.
But you have several problems in your program.
You copy all the parts that are before the index to perro. Since perro is your target array (the one bigger than the original), you have to make sure that everything gets copied to it. But instead, you only copy the parts that are before the index.
You want to place the 2 at index 1. But you wrote index=2. This means that both the 1 and 4 will be copied to perro consecutively. Your perro will look like this:
┌─┬─┬─┬─┬─┬─┐
│1│4│0│0│0│0│
└─┴─┴─┴─┴─┴─┘
0 1 2 3 4 5
and this means that you didn't put the 2 in the place you wanted it. That place is taken by the 4.
You try to copy the numbers after the index to biggie. But you are doing this using red. And in each iteration of the loop, you set red=0 again. So the only place in biggie that will change is 0, and that place will get all the numbers, and the last one will stay. So your biggie will be:
┌─┬─┬─┬─┬─┐
│8│0│0│0│0│
└─┴─┴─┴─┴─┘
0 1 2 3 4
You don't put the 2 anywhere!
You don't copy things from biggie to perro so you don`t get all the parts of the array together.
So let's look at our before and after arrays again:
Before
┌─┬─┬─┬─┬─┐
│1│4│3│7│8│
└─┴─┴─┴─┴─┘
0 1 2 3 4
After
┌─┬─┬─┬─┬─┬─┐
│1│2│4│3│7│8│
└─┴─┴─┴─┴─┴─┘
0 1 2 3 4 5
So first, we have to remember that the index we want to change is 1, not 2. Now look at the after array. You notice that there are three types of numbers:
Ones that stayed in the same place (the 1)
Ones that were added (the 2)
Ones that moved one place to the right (4,3,7,8)
How do we know which of the original numbers "stay" and which ones "move"? It's easy. The ones whose index is less than index (remember, it's 1!), that is, the one at index 0, stays.
All the others (including the one that is in the index itself!) have to move to a new place. The place is their old index + 1.
So your program should look like this:
Prepare an array whose size is one bigger than the original (like your perro).
Loop on all the indexes in the old array. Suppose the loop variable is i.
If i is less than the index, copy the number at index i from the original array to the new array at the same index, that is, at i.
For all other cases, copy the number at index i from the original array to the new array, but moved by one place. That is, i+1. There is no need for another variable or a ++ here.
When you finish that loop, your array will look like:
┌─┬─┬─┬─┬─┬─┐
│1│0│4│3│7│8│
└─┴─┴─┴─┴─┴─┘
0 1 2 3 4 5
Now don't forget to put your actual 2 there, at the index index!
Note: please give your variables meaningful names. I'm not sure, perhaps the names are meaningful in your native language, but biggie and red seem to be words in English, but they don't help us understand what these variables do. Try to use variable names that describe the function of the variable. Like original, target, temporary, nextIndex etc.

I think this is a clean and simple solution :
public static void main(String[] args) {
int[] gato = {1, 4, 3, 7, 8};
int index = 2; //store item index 2
System.out.println("the contents of gato are ");
for (int i = 0; i < gato.length; i++) {
System.out.println(gato[i]);
}
gato = Arrays.copyOf(gato, gato.length + 1);
for (int i = gato.length - 1; i > index; i--) {
gato[i] = gato[i - 1];
}
//put the element in the array
gato[index] = 2;
for (int i = 0; i < gato.length; i++) {
System.out.println(gato[i]);
}
}

Related

Java code 1+ issue

problem with Java code.
import java.util.Random;
public class arrayTable {
public static void main (String[] args) {
System.out.println("Index\t + Value");
int Array[] = new int[10];
Random Object = new Random();
int Values;
// Assigning random values to each element of array
for(int i=0; i<Array.length;i++) {
Values= (1+Object.nextInt(50));
Array[i] = Values;
}
for(int j=0;j<Array.length;j++) {
System.out.println(j + "\t" + Array[j]);
}
}
}
Here with this code i wrote (1+) next to the object so the index should start at 1, however when ever i run the code at always starts at index 0, and it does not matter if i type 2+ or 3+ pr whatever. Could anyone be helpful with pointing out the problem with the code.
thank you in advance.
i wrote (1+) next to the object so the index should start at 1
You wrote 1+ next to the value not the index!
So, what you were doing was:
array[0] = 50 + 1;
Instead of:
array[0 + 1] = 50;
If you wanted to start from index 1 you should write it here:
Array[i + 1] = Values;
However as you're inside a for loop, you could run into an ArrayIndexOutOfBoundsException, so, a better idea would be:
for(int i=1; i<Array.length;i++) { //Look the "i" was initialized with 1 and not with 0.
REMEMBER: ARRAYS START FROM 0 INDEX
If you want to "skip" the first element, then the above modification to for loop should work, but if you want it to run from 1 to 10 then it's a bad idea, because it should be from 0 to 9
You should also be careful to follow the Java naming conventions:
firstWordLowerCaseVariable
firstWordLowerCaseMethod()
FirstWordUpperCaseClass
ALL_WORDS_UPPER_CASE_CONSTANT
and use them consistently, this will make your code easier to read and understand for you and for us.
Also, try not to name your classes / variables as Java classes names:
Object or Array or List, etc might be wrong choices, also having object lowercase would be a bad idea as it's not descriptive either as suggested by #nicomp on the comments below
but when i type Array [i + 1] it still prints out from index 0, if for example i where to make i dice i would want it to start at index 1, is there no way to do this?
I think you didn't changed the for(int j=0;j<Array.length;j++) { loop, to start from 1
To make a dice I would:
Create the array with 6 slots (starting from 0)
Fill it (1 - 6) like below (inside a for loop):
dice[0] = 1;
dice[1] = 2;
...
dice[5] = 6;
//Example of for loop
for (int i = 0; i < dice.length; i++) {
dice[i] = i + 1;
}
Get a random number (between 0 - 5) called random
Get the value of the array at position random
For example:
random = 3;
//dice[random] = 4;
System.out.println(dice[random]);

Can any one give me better solution for merging two sorted arrays into another sorted array [duplicate]

This question already has answers here:
How to merge two sorted arrays into a sorted array? [closed]
(30 answers)
Closed 5 years ago.
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arrA = {2,3,4};
int[] arrB = {5,6,7,8};
mergeArray(arrA,arrB);
}
static void mergeArray(int[] arrA,int[] arrB){
int len = arrA.length+arrB.length;
int lenA = arrA.length;
int lenB = arrB.length;
int a=0,b=0,c=0;
int temp=0;
int[] arrC = new int[len];
for(int i=0; i < lenA; i++){
arrC[i] = arrA[i];
}
for(int j=lenA,k=0; (k < lenB) && (j < len) ; j++,k++){
arrC[j] = arrB[k];
}
for(int n=0; n < len ; n++){
for(int m=0; m < len; m++ ){
if(arrC[n] < arrC[m]){
temp = arrC[n];
arrC[n] = arrC[m];
arrC[m] = temp;
}
}
}
for(int x : arrC){
System.out.println(x);
}
}
Result: {2,3,4,5,6,7,8}
I am trying to put the values into one new array and sorting them again.Can any one give me better solution than this.
I recalled old school days! Here is the solution! No libraries, just plain code! Enjoy.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int [] array1 = {5, 1, 4, 5, 7, 8, 1, 0, 4};
int [] array2 = {4, 7, 1, 0, 9, 3};
System.out.println("Array 1");
print(array1);
System.out.println("Array 2");
print(array2);
Arrays.sort(array1);
Arrays.sort(array2);
System.out.println("Sorted array 1");
print(array1);
System.out.println("Sorted array 2");
print(array2);
int [] mergedAndSortedArray = mergeSorted(array1, array2);
System.out.println("Sorted merged array");
print(mergedAndSortedArray);
}
private static void print(int [] array) {
for (int i : array) {
System.out.print(i + " ");
}
System.out.println("\n");
}
private static int [] mergeSorted(int [] array1, int [] array2) {
int [] res = new int [array1.length + array2.length];
int i = 0;
int j = 0;
int k = 0;
//Do your homework. First loop until you reach end of either array, and then add the rest elements.
return res;
}
}
This is result
Array 1
5 1 4 5 7 8 1 0 4
Array 2
4 7 1 0 9 3
Sorted array 1
0 1 1 4 4 5 5 7 8
Sorted array 2
0 1 3 4 7 9
Sorted merged array
0 0 1 1 1 3 4 4 4 5 5 7 7 8 9
Update
If you need to merge N sorted arrays into a sorted one, you can merge them by pairs recursively (merge first and second arrays, third and fourth, and so on), then again, until you have two arrays, and finally merge them too!
You can use Java8 Streams:
int[] arrA = {2,3,4};
int[] arrB = {5,6,7,8};
int[] mergedArray = IntStream.concat(Arrays.stream(arrA), Arrays.stream(arrB)).toArray();
If the order is important:
IntStream.concat(Arrays.stream(arrA), Arrays.stream(arrB)).sorted().toArray();
In such case you can convert it not only to an array, but to whatever you want.
Easy. You're concatenating one array after another, then doing a bubble sort. A bubble sort is O(n^2) in the worst case. This means that the time needed to sort may increase with the square of the sum of the lengths of the two input arrays.
But you already know that the two arrays are ordered. When writing to the combined array, all you need to look at are the heads of the two input arrays. The next write will be the minimum value of the two. Your merge will be O(n), where n is the sum of the lengths of the two input arrays.
This is one part of a sorting algorithm called merge sort. Frequently a merge sort is in-place, in a single array. Yours differs slightly, with the two sorted parts in separate arrays, but the idea is the same.
Try this:
Integer[] mergeArray = (Integer[])ArrayUtils.addAll(arrA, arrB);
Checkout this:
public static T[] addAll(T[] array1, T... array2)
And then:
Arrays.sort(mergeArray, Collections.reverseOrder());
I think you're asking for a way to "zip together" two arrays that are already sorted, so that you end up with a sorted array. I think you've realised that concatenating then sorting is inefficient, because it doesn't take advantage of the input arrays being sorted already.
I also assume that this is a homework or study question, so I'm going to describe the solution at a high level.
You need a few variables to track where you are:
leftIndex (where you are on the left input)
rightIndex (where you are on the right input)
destinationIndex (where you are in the destination)
Start with all the indexes at zero. Now we're going to pick an array to work from, and take values from it one by one.
As long as those values are less than the next value from the other input array, we add it to the output. Then we switch over to the other array. We keep switching back and forth until we've reached the end of both inputs.
Pseudocode:
while (leftIndex and rightIndex are both within the length of their arrays) {
while(leftInput[leftIndex] is less than rightInput[rightIndex]) {
copy leftInput[leftIndex] into destination[destinationIndex]
increment leftIndex
increment destinationIndex
}
while(rightInput[rightIndex] is less than leftInput[leftIndex]) {
copy rightInput[leftIndex] into destination[destinationIndex]
increment rightIndex
increment destinationIndex
}
}
If you translate what I've written directly into Java, you'll probably get ArrayIndexOutOfBounds exceptions. You need to add extra code in the while statement to make it do the right thing when one of the indexes is past the end of its array.

How to know the fewest numbers we should add to get a full array

recently I met a question like this:
Assume you have an int N, and you also have an int[] and each element in this array can only be used once time. And we need to design an algorithm to get 1 to N by adding those numbers and finally return the least numbers we need to add.
For example:
N = 6, array is [1,3]
1 : we already have.
2 : we need to add it to the array.
3 : we can get it by doing 1 + 2.
4: 1 + 3.
5 : 2 + 3.
6 : 1 + 2 + 3.
So we just need to add 2 to our array and finally we return 1.
I am thinking of solving this by using DFS.
Do you have some better solutions? Thanks!
Here's an explanation for why the solution the OP posted works (the algorithm, briefly, is to traverse the sorted existing elements, keep an accumulating sum of the preceding existing elements and add an element to the array and sum if it does not exist and exceeds the current sum):
The loop tests in order each element that must be formed and sums the preceding elements. It alerts us if there is an element needed that's greater than the current sum. If you think about it, it's really simple! How could we make the element when we've already used all the preceding elements, which is what the sum represents!
In contrast, how do we know that all the intermediate elements will be able to be formed when the sum is larger than the current element? For example, consider n = 7, a = {}:
The function adds {1,2,4...}
So we are up to 4 and we know 1,2,3,4 are covered,
each can be formed from equal or lower numbers in the array.
At any point, m, in the traversal, we know for sure that
X0 + X1 ... + Xm make the largest number we can make, call it Y.
But we also know that we can make 1,2,3...Xm
Therefore, we can make Y-1, Y-2, Y-3...Y-Xm
(In this example: Xm = 4; Y = 1+2+4 = 7; Y-1 = 6; Y-2 = 5)
Q.E.D.
I don't know if this is a good solution or not:
I would create a second array (boolean array) remembering all numbers I can calculate.
Then I would write a method simulating the adding of a number to the array. (In your example the 1, 3 and 2 are added to the array).
The boolean array will be updated to always remember which values (numbers) can be calculated with the added numbers.
After calling the add method on the initial array values, you test for every Number x ( 1 <= x <= N ) if x can be calculated. If not call the add method for x.
since my explanation is no good I will add (untested) Java code:
static int[] arr = {3,5};
static int N = 20;
//An Array remembering which values can be calculated so far
static boolean[] canCalculate = new boolean[N];
//Calculate how many numbers must be added to the array ( Runtime O(N^2) )
public static int method(){
//Preperation (adding every given Number in the array)
for(int i=0; i<arr.length; i++){
addNumber(arr[i]);
}
//The number of elements added to the initial array
int result = 0;
//Adding (and counting) the missing numbers (Runtime O(N^2) )
for(int i=1; i<=N; i++){
if( !canCalculate[i-1] ){
addNumber(i);
result++;
}
}
return result;
}
//This Method is called whenever a new number is added to your array
//runtime O(N)
public static void addNumber( int number ){
System.out.println("Add Number: "+(number));
boolean[] newarray = new boolean[N];
newarray[number-1] = true;
//Test which values can be calculated after adding this number
//And update the array
for(int i=1; i<=N; i++){
if( canCalculate[i-1] ){
newarray[i-1] = true;
if( i + number <= N ){
newarray[i+number-1] = true;
}
}
}
canCalculate = newarray;
}
Edit: Tested the code and changed some errors (but rachel's solution seems to be better anyway)
It is a famous problem from dynamic programming. You can refer to complete solution here https://www.youtube.com/watch?v=s6FhG--P7z0
I just found a possible solution like this
public static int getNum(int n, int[] a) {
ArrayList<Integer> output = new ArrayList<Integer>();
Arrays.sort(a);
int sum = 0;
int i = 0;
while(true) {
if (i >= a.length || a[i] > sum + 1) {
output.add(sum + 1);
sum += sum + 1;
} else {
sum += a[i];
i++;
}
if (sum >= n) {
break;
}
}
return output.size();
};
And I test some cases and it looks correct.
But the one who write this didn't give us any hints and I am really confused with this one. Can anybody come up with some explanations ? Thanks!

Removing an element from an Array in java

So I am in the AP Computer Science class in High School so I'm not very experienced. I have a program to do that requires me to read in numbers from a file, put those numbers into an array and then remove all of the 0's from the array.
So if the numbers are: 0,2,4,6,0,5,3,5...
I would need to create an array: [0,2,4,6,0,5,3,5]
and then remove the 0's: [2,4,6,5,3,5]
I have to do this using arrays and I am not allowed to create a second array to do this. I have looked all over online and the Java API's to find a method that can remove an element from an array but I simply can't find one. If somebody has any idea of one that I can use or a direction to steer me in, your advice would be much appreciated.
THIS IS THE QUESTION WORD FOR WORD:
1. Write a program that reads a text file(compact.txt) and stores the integers in an array. Your instructor will provide this text file.
2. Write a method compact that removes all zeroes from the array, leaving the order of the elements unchanged. All local variables within this function must be scalar. In other words, you may not use a second array to solve the problem.
3. Do not solve the problem simply by printing out only the non-zero values in the array. The compact method must remove all zeroes from the array.
You could try the following: Since you cannot modify the length of the array, you can arrange it so you put all zeroes at the end of the array and with value -1 (this is optional, just to indicate they are zeroes).
public static void main(String[] args)
{
int[] arr = { 0, 1, 2, 0, 3, 0, 4, 0, 5, 6, 7 };
int[] arrWithoutZeros = compact(arr);
for (int i : arrWithoutZeros) {
System.out.println(i);
}
}
private static int[] compact(int[] arr)
{
for (int i = 0; i < arr.length; i++) {
if (arr[i] == 0) {
int j = 0;
for (j = i; j < arr.length - 1; j++) {
arr[j] = arr[j + 1];
}
arr[j] = -1;
i--;
}
}
return arr;
}
Output:
1
2
3
4
5
6
7
-1
-1
-1
-1
Note: This meets the question requirements:
Leaves the order of elements unchanged (it changes its position, but not the order)
Don't use a second array
Not solved by just printing the non-zero elements
Removes zeros from array (they are now -1)
I'm not normally a fan of doing homework, but I found this one interesting and impossible as written, so here goes.
This is much like Christian's answer, but I'm using Integer instead of int so that I can set the 0s to null instead of some other integer. I've also avoided the extra loop he has to copy every remaining value down on every single 0, instead iterating the array once and then iterating the tail only once to set the null values.
public class ArrayCompact {
private static Integer[] ARRAY = { 1, 3, 5, 0, 7, 9, 0, 2, 0, 4, 6, 0, 8, -1, 0 };
public static void main( String[] args ) {
printArray( compact(ARRAY ));
}
public static Integer[] compact( Integer[] ints ) {
int j = 0;
for ( int i = 0; i < ints.length; i++ ) {
if ( ints[i] != 0 ) {
ints[j++] = ints[i];
}
}
for ( int i = j; i < ints.length; i++ ) {
ints[i] = null;
}
return ints;
}
public static void printArray( Integer[] ints ) {
for ( Integer i : ints ) {
System.out.print( i + " " );
}
}
}
Output 1 3 5 7 9 2 4 6 8 -1 null null null null null Technically I guess you could just not print the nulls, since that's not not printing 0s...
Another Edit:
(I think previous answer is still meaningful and I am keeping it at the end. This edit is mainly for suggestion specific to the homework requirement)
Base on the question, the compact logic treat 0 as something that is "meaningless" and need to be "removed". Therefore we don't really need some kind of special value after we "shrink" the array. Simply keeping it as 0 will help.
Apart from the "copy [i+1,end] to i" method, there is another (easier and possibly faster) method that you can do to "remove" the zeros.
Basically what you need is, iterate through the array. If you encounter a 0, then find the first non-zero value after that position, and swap the zero with that non-zero value.
Which looks like this in psuedo code:
for (i = 0; i < arr.length; i++) {
if (arr[i] == 0) {
for (j = i+1; j < arr.length; j++) {
if (arr[j] != 0) {
arr[i] = arr[j];
arr[j] = 0;
break;
}
}
}
}
// arr is "shrinked" here
Then it is your choice to return an actually shrinked copy of array, or simply return the "so-called-shrinked" array with 0s at the end.
Something for you to think of:
First, in Java, size of array is fixed, therefore, it is not possible to shrink array's size. Therefore, it is IMPOSSIBLE to have a result array with less elements without creating a new array
If it is fine for you to leave unused element at the end as some special values (e.g. -ve, or 0 etc), the removing element at position i from array essentially means:
copy array elements [i+1 to end] to position i, and replace arr[end] with special empty value
e.g. [1, 3, 5, 7, 9]
If I want to remove index 2, what I need to do is to copy element 3-4 to position 2:
[1,3,5,7,9] -> [1,3,7,9,9]
^^^ ^^^
and replace end element with some special value (e.g. -1 in this example):
[1,3,7,9,9] -> [1,3,5,7,-1]
Array copy can be done easily by using System.arrayCopy()
Have just seen update in your question.
Most of my answer is still valid, and here is some extra update with regards to your question:
If you are sure that no Integer.MIN will appear in your input, then use my above mentioned approach, and update the input array accordingly.
You may consider using Integer[] instead of int[], so that you can put null
This is the most "normal" approach, but given your requirement, this may or may not be valid. The question ask you to have only scalar LOCAL VARIABLES. Which implies to me that, if I don't create another variable, I can still return another array (seems that the question is only trying to stop you using another array in process of compacting). Just follow what I have mentioned above, however, instead of replacing the end position with some special value, just keep a local var which is array length. Whenever you remove an element (by copying [i+1, 0] to position i), decrement the array length var. At the end, return a new copy of "shrinked" array by using Arrays.copyOf(oldArray, newLength).
Here is a piece of psuedo-code for point 3:
int[] compact(int[] input) {
int arrSize = input.length;
int i = 0;
while (i < arrSize) {
if (input[i] == 0) {
copy input[i+1 to end] to input[i to end-1]
arrSize--;
} else {
i++;
}
}
return Arrays.copyOf(input, arrSize);
}

Java Array exercise

I have this array exercise. I want to understand how things work, if someone can
we have the object array of type int called index with 4 elements
we have the object array of type String called islands with 4 elements
I don't understand how things are passing to each other, I need a good explanation.
class Dog {
public static void main(String [] args) {
int [] index = new int[4];
index[0] = 1;
index[1] = 3;
index[2] = 0;
index[3] = 2;
String [] islands = new String[4];
islands[0] = "Bermuda";
islands[1] = "Fiji";
islands[2] = "Azores";
islands[3] = "Cozumel";
int y = 0;
int ref;
while (y < 4) {
ref = index[y];
System.out.print("island = ");
System.out.println(islands[ref]);
y ++;
}
}
Take a pen and paper and make a table like this, and go through the iterations:
y ref islands[ret]
--- --- ------------
0 1 Fiji
1 3 Cozumel
2 0 Bermuda
3 2 Azores
Well, you've added index in the array named index then accessing the same value in while loop
int y=0;
ref = index[y]; // now ref = 1
islands[ref] // means islands[1] which returns the value `Fiji` that is stored in 1st position
First, you make an array that holds ints, the array has length 4 (4 variables can be in it):
int [] intArray = new int[4];
Your array is called index which may be confusing for the explanation. The index of an array is which "position" you are referring to and is between 0 and the length-1 (inclusive). You can use it in two ways:
int myInt = intArray[0]; //get whatever is at index 0 and store it in myInt
intArray[0] = 4; //store the number 4 at index 0
The following code does nothing more than get a number from the first array and use it to access a variable in the second array.
ref = index[y];
System.out.println(islands[ref])
To make it understand, take a paper and pen and jot down the arrays in table form and iterate through the loop to understand. (back in school days, our teacher(s) called it a dry run)
First we represent the data
Iteration y ref ( `ref = index[y]`) islands
1 0 1 Fiji
2 1 3 Cozumel
3 2 0 Bermuda
4 3 2 Azores
So you can go through the iterations
Iteration 1
y=0
ref = index[y], i.e. index[0] i.e 1
System.out.print("island = "); prints island =
System.out.println(islands[ref]); islands[ref] i.e islands[1] i.e Fiji
hence for iteration 1 output will be
island = Fiji

Categories