I want to store several 2d array positions in an ArrayList and I've set it up like so:
ArrayList<Integer> playedValues = new ArrayList<Integer>();
playedValues.add(dataArray[0][1]);
playedValues.add(dataArray[0][2]); //example of adding 2d array positions
int size = playedValues.size(); //get size of ArrayList
int gridIndex = playedValues.get(size - 1); //trying to set gridIndex to dataArray[0][2]
cell.setCell(0, gridIndex); //this is where the error occurs
//trying to pass gridIndex to here
public void setCell(int value, int gridIndex) {
gridIndex = value;
}
My issue is when I try and pass gridIndex as a parameter to setCell, I get a NullPointerException.
The method I'm passing it to seems to work fine in my tests, so I assume gridIndex is not being set properly. How do I make playedValues store dataArray[][] itself instead of the information dataArray[][] holds?
The solution you were looking for
After talking with you in chat, we determined that you were making a Sudoku game, and you wanted to store moves, and be able to undo those moves.
You have the board stored as sudokuGrid which is a 2d int array. You need to be able to make changes to certain cells (row, column). You also need to be able to store moves, (row, column), and in order. Then you can use both of these features together, and allow your users to undo their moves.
Let's focus on making changes to a cell first.
Undo'ing a move
We can write a method that takes in a row and a column, and changes the value of the cell at (row, column) back to 0. (Undo-ing a move).
We should be able to call this method like so:
int testRow = 4, testColumn = 1;
undoMove(testRow, testColumn, sudokuGrid);
Of course, later we'll use row's and column's from previous moves, but we need to be able to test right now. The undoMove method will be written like so:
public void undoMove(int row, int column, int[][] board) {
board[row][column] = 0;
}
It's very important that we pass in sudokuGrid to undoMove. Otherwise, undoMove wouldn't be able to make permanent changes to the game board. You can read the link I gave farther below for more information on why you are able to make changes to sudokuGrid.
Now, we need to focus on how we can store moves.
Storing moves
We have a few options available, but the easiest in my opinion, would be to make an ArrayList and store Move's in it. Of course, Java hasn't defined Move's for us. We will have to make our own class to define a Move.
If you're unfamiliar with making classes, you can learn the basics here, and here.
Here's what our Move class might look like:
class Move {
int row, column;
public Move(int row, int column) {
this.row = row;
this.column = column;
}
}
public void undoMove(int row, int column, int[][] board) {
board[row][column] = 0;
}
This simply says that each Move will have a row, a column.
We can now store the row and column of the cell where each move was played.
Now we can make an ArrayList to hold our Move's:
ArrayList<Move> moves = new ArrayList<Move>();
We can make a Move object each time that a user makes a move like so:
// You'll need to get the row and column
// before you make the Move object
Move currentMove = new Move(row, column);
Now anytime we want to undo a move, we can simply do this:
Move moveToUndo = moves.get( moves.size() - 1 );
undoMove(moveToUndo.row, moveToUndo.column, sudokuGrid);
moves.remove( moves.size() - 1 );
Now all together!
class Move {
int row, column;
public Move(int row, int column) {
this.row = row;
this.column = column;
}
}
public void undoMove(int row, int column, int[][] board) {
board[row][column] = 0;
}
// Later on, in your game loop method
ArrayList<Move> moves = new ArrayList<Move>();
// Adding moves
// In your program, you'll get the row and column from what
// the user types in or clicks on.
int row = 1, column = 7;
moves.add( new Move(row, column) );
row = 6, column = 8;
moves.add( new Move(row, column) );
// Undo'ing moves
Move moveToUndo = moves.get( moves.size() - 1 );
undoMove(moveToUndo.row, moveToUndo.column, sudokuGrid);
moves.remove( moves.size() - 1 );
You could even re-write the undoMove method to take in a Move, rather than a row and a column, and that would look very clean. You could also write a method undoLastMove that would automate some of this process.
Fixing your ArrayList problem
I'm not quite sure what you intend to use the ArrayList playedValues for, so I have to make a somewhat educated guess that you want to have an ArrayList hold arrays, not single values.
That is very simple to do!
Your current declaration:
ArrayList<Integer> playedValues = ArrayList<Integer>();
Sets up playedValues to hold Integer or int values. To instead set up playedValues to hold arrays of int's, do this:
ArrayList<Integer[]> playedValues = ArrayList<Integer[]>();
Then playedValues will store arrays of Integer's or int's.
You can use the ArrayList like so:
ArrayList<Integer[]> playedValues = ArrayList<Integer[]>();
int[] arrayOne = {1, 2, 3, 4, 5};
// Adding arrays to the list
playedValues.add(arrayOne);
// Iterating through all arrays in playedValues
for(int i = 0; i < playedValues.size(); i++) {
int[] currentArray = playedValues.get(i);
// Then, of course, you can loop over each array like normal:
for(int j = 0; j < currentArray.length; j++) {
System.out.println(
"Array #" + i + " - Element #" + j + " = " + currentArray[i][j]
);
}
}
There's an even better way!
If you're using an ArrayList the same way as you would a 2d array, but you still want all of the flexibility and features of an ArrayList, then do this:
ArrayList<ArrayList<Integer>> playedValues = ArrayList<ArrayList<Integer>>();
That sets up playedValues to be an ArrayList which holds ArrayLists which hold int's. Very similar to using int[][] which uses an array that holds arrays that hold ints'.
The above code can be implemented with this new ArrayList of ArrayLists, like so:
ArrayList<ArrayList<Integer>> playedValues = ArrayList<ArrayList<Integer>>();
int[] arrayOne = {1, 2, 3, 4, 5};
// Adding values to the playedValues
playedValues.add( Arrays.asList(arrayOne) );
// Iterating through all values in playedValues
for(int i = 0; i < playedValues.size(); i++) {
for(int j = 0; j < playedValues.get(i).size(); j++) {
System.out.println(
"Row #" + i + " - Column #" + j + " = " + playedValues.get(i).get(j)
);
}
}
If you wanted to store, maybe a 9x9 grid, you could easily do that like this:
ArrayList<ArrayList<Integer>> playedValues = ArrayList<ArrayList<Integer>>();
int[] sampleRow = {0, 0, 0, 0, 0, 0, 0, 0, 0};
for(int i = 0; i < 9; i++) {
playedValues.add( Arrays.asList(sampleRow) );
}
But, should you use ArrayList?
I don't see a huge need for using an ArrayList here. When I see the code you have and read what you are trying to do, I immediately think 2d array.
There isn't anything in your code, or my answer, that can't be done with a 2d array. It may make things simpler too. The only issue, is if you need to dynamically add arrays. A 2d array can't do that.
Here is the same implementation as above, with a 2d array:
// 100 for rows and columns was chosen arbitrarily.
int[][] playedValues = new int[100][100];
int[] arrayOne = {1, 2, 3, 4, 5};
int[] arrayTwo = {1337, 9001, 1111111, 22222, 33333, 444, -1, -123, 246};
// Adding arrays to the list
playedValues[0] = arrayOne;
playedValues[1] = arrayTwo;
// Iterating through all arrays in playedValues
for(int i = 0; i < playedValues.length; i++) {
for(int j = 0; j < playedValues[i].length; j++) {
System.out.println(
"Array #" + i + " - Element #" + j + " = " + currentArray[i][j]
);
}
}
And the setCell method:
public void setCell(int value, int row, int column, int[][] grid) {
grid[row][column] = value;
}
Fixing the setCell method
If we have an ArrayList which stores arrays of int's, we can change a certain cell with this implementation:
// Making a call to set the cell in the 1st row at the 4th column, to 0
setCell(0, 1, 4, playedValues);
public void setCell(int value, int row, int column, ArrayList<Integer[]> grid) {
int[] rowArray = grid.get(row);
rowArray[column] = value;
}
Original Error
The problem isn't with gridIndex, it's with cell.
You can get a NullPointerException from an int, since all int's have default/null values of 0 in Java. See the documentation here, here, here, and this post's answers, for proof of this.
So the problem isn't with the setCell method, it's with your cell variable. The NullPointerException is being thrown because cell is null, not anything you pass to setCell.
Why setCell didn't originally work
It is true, as pointed out by other answers, that the method setCell won't actually do anything noticeable. This is because Java is pass by value, not pass by reference. You can read this post for a detailed explanation.
What this means behind the scenes, is that whatever actual number values you pass to setCell as value and gridIndex, setCell will have the values of, but not the references.
This code:
int gridIndex = 10, myValue = 2;
setCell(myValue, gridIndex);
will call setCell and pass the values of gridIndex and myValue, which are 10 and 2. The setCell method never sees the actual variables gridIndex and myValue, setCell has no reference to those variables, it only ever sees the values 10 and 2.
This can be confusing because the values are stored in variables within setCell, the variables you specify to be the parameter names (int value, int gridIndex), but these variables, are not the variables you passed to setCell. See this code:
public static void main(String[] args) {
int gridIndex = 10, myValue = 9999;
setCell(myValue, gridIndex);
System.out.println(gridIndex);
}
public static void setCell(int value, int gridIndex) {
// In here, value is NOT the same variable, myValue, that
// we passed in. Just the same, gridIndex, is not the same
// variable that we passed in from main.
// In here, value and gridIndex have the SAME VALUES
// as the variables we pass in, but they are not the same
// variables. They are newly made variables, with the same values.
}
Also look at this code:
public static void main(String[] args) {
setCell(10, 9999);
System.out.println(gridIndex);
}
public static void setCell(int value, int gridIndex) {
gridIndex = value;
}
We didn't pass a variable to setCell, but inside setCell we changed the variable gridIndex to be equal to value. Will this tell Java that the new value of the number 9999 should really be 10? Of course not. We aren't changing what was passed in, we are changing variables that hold the values that were passed in.
An easy way to think about what is happening, is to remember that whenever you use an int variable in Java, you could replace the variable name with the value it holds, and the code would remain exactly the same.
Take this code for example:
int gridIndex = 10, myValue = 9999;
setCell(myValue, gridIndex);
an equilivant code is:
setCell(10, 9999);
And as we just saw above, of course we can't change the value of 10 or 9999. We can't just decide that numbers are equal other numbers. Of course we can change the numbers that are held in int's, but there aren't any int variables being delivered to setCell, only number values like 10 or 9999.
public void setCell(int value, int gridIndex) {
gridIndex = value;
}
The above code does nothing. It takes two arguments, and locally sets one of the arguments to the other. Then since both of the variables were declared within the function, they are both gone when it exits.
Since this method just sets gridIndex, why not just set it directly?
gridIndex = 0;
EDIT: example of why this doesn't work.
I tried this in my IDE - it is exactly the same setCell method you have.
public static void main(String[] args) {
int gridIndex = 10;
setCell(0, gridIndex);
System.out.println(gridIndex);
}
public static void setCell(int value, int gridIndex) {
gridIndex = value;
}
The console prints 10, because setCell does nothing. It doesn't set the value of gridIndex, it doesn't edit any variables. It does nothing, because the only values it changes are values which are declared in its signature, and which are lost when the method exits as a result.
Related
I'm beginner programmer, I have fallen into a rabbit hole trying to understand how to use arrays. I'm trying to create a table using multidimensional arrays and I am looking to create a table with 7 rows and 5 columns.
column 1 = will take values from the user input.This input is stored in an array.
column 2 = will print the highest input in that array.
column 3 = will print the lowest input in that array
column 4 = will print take the increment Total. i.e current input + previous input.
column 5 = will take the increment average. i.e Total/Index
Complete Code below
import java.util.Scanner;
public class Numbers {
public static void main(String[] args)
{
//----User Input - Add values to array ----//
Scanner keyboard = new Scanner(System.in);
int places = 7;
int [] values = new int [places];
int sum = 0;
System.out.println("Enter a Numbers:");
for (int count = 0; count < places; count++)
{
values[count] = keyboard.nextInt();
System.out.println(values[count]);
}
//----------------Total---------------------//
for (int numb : values)
{
sum = sum + numb;
}
System.out.println("\n Total:" + sum);
//----------Average------------------------/
double avg = 0;
if (values.length > 0)
{
avg = sum / values.length;
}
System.out.printf("\n Average:"+ avg);
//---------Table Start---------------------//
int [] [] table = new int [7][5];
for (int row =0; row < 7; row++)
for (int column = 0; column < 5; column++)
table [row][column] = getTable(column, column, column, column, avg);
System.out.println("\n\nIndex\tInput\tHigest\tLowest\tTotal\tAverage");
for (int row = 0; row < 7; row++)
{
System.out.print((row + 1) + " ");
for (int column = 0; column < 5; column++)
System.out.print("\t " + table[row][column] + " ");
System.out.println();
}
}
public static int getTable(int input, int highest, int lowest, int total, double average) {
/* TO DO:
* - add each user input from values array into Input column
*
* - add highest/lowest values in the Highest/Lowest column
*
* - add each of the array element total in Total column - this column should take previous Total plus current total.
* i.e Total = Total + Input
*
* - add Average - Current average value.
*/
return 0;
}
}
What I don't know is how to get my code to fill each of the rows using different values each time.
For Example:
Index 1
1st column take first value of the values array
2nd column: take highest value of the values array
3rd column: take lowest value of the values array
4th column: take previous element of values array plus the current value
5th column: take total/index
I know that may need to create a method to get my program to loop through but I just don't know how to do it. I've tried a few different ways, but I'm just getting confused. In the left corner of the screenshot below, is how the columns would look like. Notice how they are all returning 0, which I known that is coming from the getTable method that I created, which is doing just that.
Basically, in this code, you're looping over all the columns:
for (int row =0; row < 7; row++)
for (int column = 0; column < 5; column++)
table [row][column] = getTable(column, column, column, column, avg);
You don't want to do this. Looping over all the columns would make sense if you were doing pretty much the same thing with each column. But you're not. You want each column to have the result of a very different computation. So it would make more sense to say something like
for (int row = 0; row < table.length; row++) {
table[row][0] = getFirstValue(values);
table[row][1] = getHighestValue(values);
table[row][2] = getLowestValue(values);
...
and so on. (However, I don't really understand how "values" is supposed to be used. You're inputting one set of values, but you're creating a table with 7 rows based on that one set of values. Perhaps there's more things wrong with your code.)
Note a couple of things: (1) I replaced 7 with table.length in the loop. table.length is the number of rows, and will be 7. But if you change things to use a different number of rows, then using table.length means you don't have to change the for loop. (2) My code passes values as a parameter to the different methods, which is necessary because the methods will be making computations on the input values. Your code didn't pass values to getTable(), so there's no way getTable() could have performed any computations, since it didn't have the data.
The code could be improved further. One way would be to define constants in the class like
private static final int FIRST_VALUE_COLUMN = 0;
private static final int HIGHEST_VALUE_COLUMN = 1;
...
table[row][FIRST_VALUE_COLUMN] = getFirstValue(values);
table[row][HIGHEST_VALUE_COLUMN] = getHighestValue(values);
which would be more readable.
A more significant improvement would be not to use a 2-D array at all. Since you have five values with different meanings, the normal approach in Java would be to create a class with five instance variables to hold the computed data:
public class ComputedData {
private int firstValue;
private int highestValue;
private int lowestValue;
public void setFirstValue(int firstValue) {
this.firstValue = firstValue;
}
public int getFirstValue() {
return firstValue;
}
// similarly for other fields
}
table would then be a 1-dimensional array of ComputedData.
This is better because now you don't have to assign meaningless column numbers to different computed values. Instead, the names tell you just what each computed value is. Also, it means you can add new values later that don't have to be int. With an array, all elements in the array have to be the same type (you can use Object which can then hold a value of any type, but that can make the code messier). In fact, you may decide later that the "average" should be a double instead of an int since averages of integers aren't always integers. You can make this change pretty easily by changing the type of an instance variable in the ComputedData class. If you use an array, though, this kind of change gets pretty complicated.
I am trying to solve the following problem: "Write an algorithm to print all the ways of arranging eight queens on an 8x8 chess board so that none of them share the same row, column or diagonal (i.e. no two queens attack each other.)"
I am having trouble understanding why the author used Integer[] instead of the more common int[], for example in "Integer[] columns" and "ArrayList results" which are parameters to placeQueens. My hypothesis is that this is due to generics in Java, but I'm not entirely sure.
Code snippet below. Link to complete code at bottom of page.
public static int GRID_SIZE = 8;
/* Check if (row1, column1) is a valid spot for a queen by checking if there
* is a queen in the same column or diagonal. We don't need to check it for queens
* in the same row because the calling placeQueen only attempts to place one queen at
* a time. We know this row is empty.
*/
public static boolean checkValid(Integer[] columns, int row1, int column1) {
for (int row2 = 0; row2 < row1; row2++) {
int column2 = columns[row2];
/* Check if (row2, column2) invalidates (row1, column1) as a queen spot. */
/* Check if rows have a queen in the same column */
if (column1 == column2) {
return false;
}
/* Check diagonals: if the distance between the columns equals the distance
* between the rows, then they're in the same diagonal.
*/
int columnDistance = Math.abs(column2 - column1);
int rowDistance = row1 - row2; // row1 > row2, so no need to use absolute value
if (columnDistance == rowDistance) {
return false;
}
}
return true;
}
public static void placeQueens(int row, Integer[] columns, ArrayList<Integer[]> results) {
if (row == GRID_SIZE) { // Found valid placement
results.add(columns.clone());
} else {
for (int col = 0; col < GRID_SIZE; col++) {
if (checkValid(columns, row, col)) {
columns[row] = col; // Place queen
placeQueens(row + 1, columns, results);
}
}
}
}
Source for question/code: Cracking the Coding Interview. Link to complete code: https://github.com/gaylemcd/ctci/blob/master/java/Chapter%209/Question9_9/Question.java
In Java, Integer represents an object, while int is a primitive type. The Integer class supports more functions and can hold null values. In addition, ArrayList can only contain objects such as Integer.
ArrayList<int[]> results = new ArrayList<int[]>();
In the revised code above, int[] would still work because it is considered an object. However, the author may be seeking consistency or would need the extra functionality of the Integer object. It is a matter of the author's preference or ignorance.
You may think that the first line of the main (from the link you've provided):
ArrayList<Integer[]> results = new ArrayList<Integer[]>();
Must use Integer, but as comments suggest, it's not the case.
ArrayList<int[]> results = new ArrayList<int[]>();
Would also worked. So it's just the author's preference in that case.
Assume that I already have a 2D int value[i][j]. This works well and I can store a single int in each index. Now I want to add a second array int data[i][j] so I can store multiple int data in it. Am I approaching it correctly?
For example in a Sudoku situation:
value[0][0] = 0
But in an other grid I have all possible values in each index
data[0][0] = {1,2,3,4,5,6,7,8,9}
Is it possible to do that? If so what should I do with my data? I'm really confused about arrays, multi-dimensional arrays, ArrayLists, etc. I'm unsure which to use.
For example:
Values {1,2,3},{4,5,6},{7,8,9}
In an 3x3:
1,2,3
4,5,6
7,8,9
Data{1,2,3,4,5,6,7,8,9}
Which I want to store it now in each grid and will have a method to remove from that list in later steps because I'm cancelling those possibilities in that grid. And the data in data{} doesn't have to be shown to the user.
I hope this will clear to some extent
Internally, Java stores 2 dimensional arrays as an array of arrays:
Suppose you have
int [][] nums = new int[5][4];
The above is really equivalent to a 3-step process:
int [][] nums;
// create the array of references
nums = new int[5][];
// this create the second level of arrays
for (int i=0; i < nums.length ; i++)
nums[i] = new int[4]; // create arrays of integers
Simply use boolean[] for possible choices. You could use Set (http://docs.oracle.com/javase/7/docs/api/java/util/Set.html), but for a small pool of fixed size with boolean options only, Set is an overkill (mainly due to code overhead).
Next thing is, that the basic principle of OOP (and Java is, or at least should be OOP) is that you should group data into objects/classes based on their functionality. If you're trying to aggregate a cell in a grid, you should create a grid (2D array) of objects, not a couple of int or boolean (or whatever) arrays.
First create a class, e.g.
class Cell {
final int POSSIBILITES = 9;
int actual_value;
boolean[] possible_values = new boolean[POSSIBILITES]; // for each number
Cell( int actual_value ) {
this.actual_value = actual_value;
for( int i = 0; i < POSSIBILITES; i++ )
possible_values[i] = true;
}
}
and then initialize/instantiate an array of objects
//...
final int X_SIZE = 9, Y_SIZE = 9;
Cell[][] cells = new Cell[X_SIZE][Y_SIZE];
for( int i = 0; i < X_SIZE; i++ )
for( int j = 0; j < Y_SIZE; j++ )
cells[i][j] = new Cell( somevalue );
//...
And then access them by, for example
//note: it's more proper to use getter/setter pattern, so this is only a crude example
if ( cells[3][6].actual_value = 7 )
do_something();
cells[1][2].possible_values[0] = false; // we're numbering from 0 to 8, so value 1=> index 0, 2=>1... 9=>8
cells[1][2].possible_values[4] = true;
Yes, it is possible. For that I'd recommend a boolean[][][] where, for example, theArray[6][3][8] is a boolean indicating whether the number 8 is included in the cell at row 6, column 3.
This is the question i am trying to solve:
Write a class called ArrayHistogram, which contains a main method and a static method called histogram, which has the following signature:
public static int[] histogram(int[][] arrayA)
In the main method, declare and initialize a two dimensional array, call it arrayA. This array must contain some non-negative integer numbers. The histogram method accepts arrayA and puts the frequency of occurrence of elements of arrayA into a one dimensional array (histA) and returns histA. Frequency of occurrence means, the number of times an element occurs in the array. Your program should work for a ragged array, as well. Your program should determine the size of the histA automatically, before declaring the variable histA.
Hint: Figure 1 shows a sample 2D array(arrayA) and the corresponding histA. histA[0] = 2 shows that 0 occurred twice in A. Or, histA[3] = 1, shows that number 3 appeared once in A.
I have done this so far
public class ArrayHistogram
{
public static void main (String[]args)
{
// declearing and initializing a 2D array.
int [][] arrayA = {{5,8,8,4,3},{1,4,2,2,3},{7,4,6,6,9}};
histogram(arrayA);
}
public static int[] histogram (int [][] arrayA)
{ // nested for loop to go through the array.
int max = 0;
for ( int row = 0; row<arrayA.length; row++){
for ( int col=0; col < arrayA[row].length; col++){
if ( arrayA[row][col]> max ){
max = arrayA[row][col];
}
}
}
int histA[] = new int [max];
for ( int row = 0; row<arrayA.length; row++){
for ( int col=0; col < arrayA[row].length; col++){
histA[arrayA[row][col]]++;
}
}
System.out.println(histA);
return histA;
}
}
This line:
histA[arrayA[row][col]]++;
shows a java.lang.ArrayIndexOutOfBoundsException
First am I doing this right?
If not how should I make it happen?
Keep in mind that arrays are indexed starting at 0, so your max value is not going to be an index available in your histA array. One way to fix this is create your array like so:
int histA[] = new int[max + 1];
In your second loop, when you hit row being 2 and col being 4 it's going to attempt to use histA[9] which isn't a valid index in that array unless you define your array to be of size 10, which in your case is max + 1.
length is an attribute of array objects which returns the size. Now since you are looping your array starting from 0 to the length of array, its referring to the index of array which doesn't even exists. Hence an ArrayIndexOutOfBoundException.
Just update your for loop termination expression to arrayA.length-1 and arrayA[row].length-1 and it will all be working fine.
Also for all such exceptions just check their Java Doc and you will get your answer.
Here's what the layout is
index num
0 [10]
1 [20]
2 [30]
(Add 35 here)
3 [40] Move elements down
4 [50]
5 [60]
6 [70]
then my method is this
public static void method(int[] num, int index, int addnum)
{
}
How can i add 35 in there?
Tried this:
public static void method(int[] num, int index, int addnum)
{
int index = 10;
for(int k = num.length k>3; k++)
{
Num[k]=num[k++]
}
Num[3] = 35;
As this is something you should accomplish yourself, I will only provide the method to implement it, not the code:
If you would set the number at position index, you would overwrite the value that was there previously. So what you need to do is move every element one position towards the end of the array starting from index: num[x] becomes num[x+1], etc.
You will find out that you need to do this in reverse order, otherwise you will fill your array with the value in num[index].
During this process you will need to decide what to do with the last entry of the array (num[num.length - 1]):
You could just overwrite it, discarding the value
You could return it from your function
You could throw an exception if it is non-zero
You could create a new array that is 1 entry larger than the current array instead to keep all values
etc.
After this, you have duplicated num[index]: the value is present in num[index+1], too, as you have moved it away.
Now it is possible to write the new value at the desired position without overriding an existing value.
EDIT
You have several errors in your code:
You increment k, you need to decrement it (k--, not k++)
You modify k again in your loop body: it is updated twice in each cycle
If you start with k = num.length, you will try to write at num[num.length + 1], which is not possible
Very crudely, you want to do something like this:
public static void(int[] num, int index, int addnum)
{
// initialize new array with size of current array plus room for new element
int[] newArray = new int[num.length + 1];
// loop until we reach point of insertion of new element
// copy the value from the same position in old array over to
// same position in new array
for(int i = 0; i < index; i++)
{
newArray[i] = num[i];
}
i = i + 1; // move to position to insert new value
newArray[i] = addnum; // insert the value
// loop until you reach the length of the old array
while(i < num.length)
{
newArray[i] = num[i-1];
}
// finally copy last value over
newArray[i + 1] = num[i];
}
You need to
allocate a new array with room for one new element.
int[] newArray = new int[oldArray.length + 1];
Copy over all elements and leave room for the one to insert.
for (int i = 0; i < newArray.length - 1; i++)
newArray[i < insertIndex ? i : i + 1] = oldArray[i];
Insert 35 in the empty spot.
newArray[insertIndex] = numberToInsert;
Note that it's not possible to do in a method like this:
public static void method(int[] num, int index, int addnum)
^^^^
since you can't change the length of num.
You need to allocate a new array, which means that need to return the new array:
public static int[] method(int[] num, int index, int addnum)
^^^^^
and then call the method like this:
myArr = method(myArr, 3, 35);
Since this very closely resembles homework what you need to realize is that you cannot dynamically increase the size of an array. So in your function:
public static void(int[] num, int index, int addnum)
{
int[] temp = new int[num.length *2];
for(int i = 0; i < index; i++)
copy num[i] into temp[i]
insert addnum into temp[index]
fill temp with remaining num values
}
That pseudocode above should get you started.
What you're looking for is an insertion sort.
It's classwork, so it's up to you to figure out the proper code.
Well, you can't unless there is "extra space" in your array, and then you can shift all elements [starting from index] one element to the right, and add 35 [num] to the relevant place.
[what actually happen is that the last element is discarded out].
However - a better solution will probably be to use an ArrayList, and use the method myArrayList.add(index,element)
How about this?
public class test {
public static void main(String[] arg) throws IOException
{
int[] myarray={1,2,3,5,6};//4 is missing we are going to add 4
int[] temp_myarray=myarray;//take a temp array
myarray=addElement(myarray,0);//increase length of myarray and add any value(I take 0) to the end
for(int i=0;i<myarray.length;i++)
{ if(i==3) //becaues I want to add the value 4 in 4th place
myarray[i]=4;
else if(i>3)
myarray[i]=temp_myarray[i-1];
else
myarray[i]=temp_myarray[i];
}
for(int i=0;i<myarray.length;i++)
System.out.print(myarray[i]);//Print new array
}
static int[] addElement(int[] arr, int elem) {
arr = Arrays.copyOf(arr, arr.length + 1);
arr[arr.length - 1] = elem;
return arr;
}
}