null last element in 2D array - java

I have the following 2D array:
private static Object[][] myClass = new Object[6][5];
and I am looking to null the last element in the array (myClass[lastIndex][all indexes] = null) using the following code:
for(int y = 0;y < 5;y++) {
myClass[5][y] = null;
}
However it seems to be deleting the last two elements in the array, what is causing this?
EDIT:
array print out before delete:
one
1
1
1
1.0
two
2
2
2
2.0
three
3
3
3
3.0
four
4
4
4
4.0
five
5
5
5
5.0
six
6
6
6
6.0
After "deleteing" element one(In practise I want to "delete" element one by copying all the elements down one index and setting the last to null):
two
2
2
2
2.0
three
3
3
3
3.0
four
4
4
4
4.0
five
5
5
5
5.0
null
null
null
null
null
null
null
null
null
null
My full delete code:
public void deleteStudent(int studentChoice) {
for(int i = studentChoice;i < myClass.length - 1;i++) {
myClass[i] = myClass[i+1];
}
myClassCount = myClassCount - 1;
for(int y = 0;y < 5;y++) {
myClass[5][y] = null;
}
}
int studentChoice is the index of the array.
myClassCount is a variable that's incremented/de-incremented as elements are added/deletted

This is a subtle problem:
When you copy down, the references are copied, not the values in the array so that in the last step, because you don't overwrite myClass[5], myClass[5] == myClass[4] so that any changes you then make to any element in myClass[5] are replicated in myClass[4] as they are the same object! Therefore when you null each object in myClass[5], you are nulling everything in myClass[4] aswell. This can be avoided by copying the individual values down, rather than just the arrays.
You can copy the values down like this:
for(int i = studentChoice;i < myClass.length - 1;i++) {
for(int y = 0;y < 5;y ++){
myClass[i][y] = myClass[i+1][y];
}
}
As a side note, this behavior can be demonstrated by the following:
Object[] array1 = {1};
Object[] array2 = array1;
array2[0] = 2;
System.out.println(array1[0]);//Prints 2

Related

Filling in 2D Array into 3D Array in Java

I want to write a Method where I get a 3x6 workingArray (but might also be 3x5, 3x4...) and a 3x3 (maybe also different size) filteringArray and make an 3D Array (holdArrays) where I put in the first Array to make a square (in this case 3x3), then move one position and put in another 3x3, till the last column of workingArray has been covered.
Somehow I get an nullPointerException in '//affected line' and I can't see why. So I wonder if I do this the right way and I haven't found resources for how to put 2D Arrays into 3D Array.
Example:
1 2 3 4 1 2 3 2 3 4
5 6 7 8 to 5 6 7 and 6 7 8
9 1 2 3 9 1 2 1 2 3
private static void filtering(double[][] workingArray, double[][] filteringArray) {
// creating amount of holdArrays to work with filterArray
double[][][] holdArrays = new double[workingArray.length - filteringArray.length + 1][filteringArray.length][];
// filling in the parted workingArray into holdArrays
for (int i = 0; i < holdArrays.length; i++) {
for (int j = 0; j < filteringArray.length; j++) {
for (int k = 0; k < filteringArray[j].length; k++) {
holdArrays[i][j][k] = workingArray[j][k]; //affected line
}
}
}
}
The size of the last dimension is not specified. And since the line
holdArrays[i][j][k] tries to access the kth element which is not there, it throws a Null Pointer Exception.
double[][][] holdArrays = new double[workingArray.length - filteringArray.length + 1][filteringArray.length][];

Java Copying Data from Array Rather than Reference

In the following code, I am trying to duplicate the 2d array 'cur,' swapping two values in the array, and eventually add it to an arraylist I will be using later in the program. My problem is, every time I switch these values in the array 'temp' (has the cloned values of 'cur') it also switches the values in the array 'cur.' I'm confused because I have tried clone(), Arrays.copyof, even made a new constructor for the PuzzleNode class that takes the values from cur, yet every time 'cur' doesn't reset to its original value when the iteration of the loop finishes. Any help is much appreciated.
Here's the code:
//generate the puzzles and swap the tiles
for (int i = 0; i < possibleSwaps.size(); i++) {
//stores the 2d array of Nodes
PuzzleNode temp = new PuzzleNode();
//instantiate the 2d array and populate it with values of cur
temp.puzzle = new Node[cur.puzzle.length][cur.puzzle[0].length];
for (int j = 0; j < cur.puzzle.length; j++) {
temp.puzzle[j] = cur.puzzle[j].clone();
}
for (int j = 0; j < cur.puzzle.length; j++) {
for (int k = 0; k < cur.puzzle[0].length; k++) {
if (temp.puzzle[j][k].value == possibleSwaps.get(i).value) {
//switch the values, values should always be distinct
int prev = temp.puzzle[zeroNode.x][zeroNode.y].value;
temp.puzzle[zeroNode.x][zeroNode.y].value = possibleSwaps.get(i).value;
temp.puzzle[possibleSwaps.get(i).x][possibleSwaps.get(i).y].value = prev;
}
}
}
//prints out the 2d array that should be the same everytime. But isn't
printPuzzle(cur.puzzle);
}
Example of Print Out:
(Original 2d array I want to always have)
1 2 3
4 6 8
7 [] 5
(Switched the [] and the 6, I NEED the [] to remain where it originally was in the previous iteration, so it can be swapped with the 5 and 7 in the next iterations)
1 2 3
4 [] 8
7 6 5
(Stays where it was swapped in the previous iteration)
1 2 3
4 [] 8
7 5 6
1 2 3
4 [] 8
5 7 6

How to insert a number into an array in 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]);
}
}

Array gets overwritten for no apparent reason

Problem
I have written a loop in which I fill an array with Sum objects. Everything works fine, but as soon as the loop gets to the next iteration it overwrites the first index of the array.
What have I tried
I tried to see if maybe my problem resides in a different piece of code (such as my Sum class). But could not find anything that would disturb the loop.
I tried to find other variables with the same name (even in other methods, since I was desperate) and see if I maybe changed my iterator somewhere else. I couldn't find anything related to that.
I tried looking around on the internet and SO to find something related to accidentally overwriting arrays but couldn't find anything either.
Code
public Task(Object[] parameters)
{
this.number_of_sums = Integer.parseInt((String)parameters[0]);
this.variables_per_sum = Integer.parseInt((String)parameters[1]);
this.sum_parameters = new Object[this.variables_per_sum];
this.sums = new Sum[this.number_of_sums];
int z = 0;
for(int i = 0; i < this.number_of_sums; i++)
{
int x = 0;
for(int j = (2 + z); j < ((this.variables_per_sum + 2) + z); j++)
{
this.sum_parameters[x] = parameters[j];
x++;
}
this.sums[i] = new Sum(this.sum_parameters);
System.out.println("Index 0: "+sums[0]); //1st iteration: 1 + 1 //2nd iteration: 2 - 1
System.out.println("Index 1: "+sums[1]); //1st iteration: null //2nd iteration: 2 - 1
z += this.variables_per_sum;
}
}
Expectations
I'm expecting the output of 1 + 1 and 2 - 1. I am however getting the following: 2 - 1 and 2 - 1 when I'm done.
If anyone spots anything I'm doing wrong or would like to see more information or code on my side please say so. Thanks in advance.
I'm going to assume the Sum class doesn't store its sum, but instead computes it from the array it was constructed with whenever it's needed.
It looks like all the Sum objects will share the same array -- you're passing the same reference every time you construct a Sum. Furthermore, every time you loop over j you overwrite the contents of that array.
So when everything is done, all the sums are the same.
You should be able to get around this by giving each Sum a different sum_parameters:
public Task(Object[] parameters)
{
this.number_of_sums = Integer.parseInt((String)parameters[0]);
this.variables_per_sum = Integer.parseInt((String)parameters[1]);
this.sums = new Sum[this.number_of_sums];
int z = 0;
for(int i = 0; i < this.number_of_sums; i++)
{
Object[] sum_parameters = new Object[this.variables_per_sum];
int x = 0;
for(int j = (2 + z); j < ((this.variables_per_sum + 2) + z); j++)
{
sum_parameters[x] = parameters[j];
x++;
}
this.sums[i] = new Sum(sum_parameters);
System.out.println("Index 0: "+sums[0]); //1st iteration: 1 + 1 //2nd iteration: 2 - 1
System.out.println("Index 1: "+sums[1]); //1st iteration: null //2nd iteration: 2 - 1
z += this.variables_per_sum;
}
}
Each one of your Sum objects is constructed with this.sum_parameters as a parameter:
this.sums[i] = new Sum(this.sum_parameters);
When sum_parameters is modified in each iteration of the outer loop, it changes internally in the objects constructed around references to it.
You should make an internal copy of sum_parameters in each Sum object.

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