I am trying to resize an array by adding the array size by 1 per method invoke.
I have created a static method and it takes array as its argument.
public static void addArray(int arrayName[]) {
int tempNum[] = new int[arrayName.length]; // save the numbers before add array size
for (int i = 0; i < arrayName.length; i++) { // because by adding/removing array size, it would clear element array
tempNum[i] = arrayName[i];
}
arrayName = new int[arrayName.length + 1]; // adds array size by 1
for (int i = 0; i < arrayName.length - 1; i++) { // sets all the saved numbers to the new element in the array
arrayName[i] = tempNum[i]; // stops at (length - 1) because I want to leave it blank at the last element
}
}
(sorry if the code is messed up, I don't know how to properly post code in here)
In the main, I do this;
public static void main(String[] args) {
int num[] = {0, 1, 2, 3, 4};
addArray(num);
System.out.println(num.length);
}
As you can see, the default array size (length) should be 5, but no matter how many times I invoke the method, it always print as 5.
Now I'm starting to think that static method does not allow the array from main to be resized ?
If it can't, do you have another way to resize an array by specifically using static method only ?
You need to return the array from the function:
public static int[] addArray(int arrayName[]) {
...
arrayName = new int[arrayName.length + 1]; // adds array size by 1
...
return arrayName;
}
public static void main(String[] args) {
int num[] = {0, 1, 2, 3, 4};
num = addArray(num);
System.out.println(num.length);
}
You can simply do this:
int num[] = {0, 1, 2, 3, 4};
num = Arrays.copyOf(num, num.length + 1);
System.out.println(num.length);
This should then print 6.
The issue with your code is that when you call a method, the method receives a copy of the reference. Thus, the method cannot change what object is referenced by the variable in the calling method.
Another approach is to make num a static field::
static int num[] = {0, 1, 2, 3, 4};
public static void main(String[] args) {
addArray(); // or use Arrays.copyOf() as above
System.out.println(num.length);
}
public static void addArray() {
int tempNum[] = new int[num.length + 1];
System.arraycopy(num, 0, tempNum, 0, num.length);
num = tempNum;
}
What you can't do (without complex reflection code) is pass a variable name to the method and have it change the length of an array with that name.
Related
is there a possibility in java to count the number of passed arguments into a method?
Got something like this:
public class practise7 {
public static void main(String[] args) {
int[] array3 = new int[]{1};
int[] array4 = new int[]{1, 3, 4};
int[] array5 = new int[]{2, 3,};
combine(array3, array4, array5);
}
public static void combine(int[] array3, int[] array4, int[] array5) {
//Here i need the number of passed arguments (here 3 e.g.)
int count = args.length; //found this on google but didn't worked
System.out.println(count);
}
}
Thanks a lot!
Try this. It uses the var...arg syntax.
public static void main(String[] args) {
int[] array3 = new int[]{1};
int[] array4 = new int[]{1, 3, 4};
int[] array5 = new int[]{2, 3,};
combine(array3, array4, array5);
}
// uses the variable arguments syntax
public static void combine(int[]...v) {
//Here i need the number of passed arguments (here 3 e.g.)
int count = v.length;
System.out.println(count);
for (int[] k : v) {
System.out.println(Arrays.toString(k));
}
}
}
Prints
3
[1]
[1, 3, 4]
[2, 3]
Note that combining arrays and non-arrays in the argument list can sometimes provide unexpected results. The variable syntax argument must be the last one in the signature.
Your solution doesn't work because with 'args.length' you can only get the number of arguments that were passed in the main function. You can use variable arugments feature of Java as follows:
public static void combine(int[] ... arrays)
{
int count = arrays.length;
System.out.println(count);
}
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.
That's how I'd do it in the most minimalistic way.
You might need to adjust because I didn't spend that much time on it.
However it should give you a big boost.
Remember an int[] array cannot have nulls. So I've taken an "empty" value to be zero.
Follow the comments!
static int[] addAtIndex(
final int[] array,
final int value,
final int index) {
if (array == null || array.length == 0) {
// We cannot do anything.
// Simply return to the caller
return array;
}
// This is the array reference holder
int[] localArray = array;
// Get the last element of the array
final int last = localArray[localArray.length - 1];
// Is the last element 0? Remember an int array cannot contain nulls
if (last == 0) {
if (array[index] != 0) {
// We need to shift everything to the right
// to give space to the new element
shiftRight(localArray, index);
}
} else {
// Create a bigger array of length = actualLength + 1
// and assign it to the reference holder
localArray = new int[array.length + 1];
// Copy the array elements to the new array, leaving a space
// for the new element
copyArrayAndLeaveSpace(index, array, localArray);
}
// Assign the new value
localArray[index] = value;
// Return the modified array reference
return localArray;
}
static void shiftRight(
final int[] array,
final int index) {
System.arraycopy(array, index, array, index + 1, array.length - index - 1);
}
static void copyArrayAndLeaveSpace(
final int index,
final int[] array,
final int[] newArray) {
System.arraycopy(array, 0, newArray, 0, index);
System.arraycopy(array, index, newArray, index + 1, array.length - index);
}
Usage
final int[] nums = {1, 2, 3, 4, 5, 6, 8, 9, 0};
final int[] result = addAtIndex(nums, 7, 4);
Output: [1, 2, 3, 4, 7, 5, 6, 8, 9]
final int[] nums = {1, 2, 3, 4, 5, 6, 8, 9, 1};
final int[] result = addAtIndex(nums, 7, 4);
Output: [1, 2, 3, 4, 7, 5, 6, 8, 9, 1]
I have a function called tournamentTreeKSelection which finds the K-th largest element in an array. The function takes three parameters, the array, the same array again and the value of K. The purpose of sending two copies of the array is so that during recursive calls, I can modify one copy of the array and still keep the original array I sent in during that call. Here is the code:
import java.util.ArrayList;
import java.util.Arrays;
public class TournamentTree {
public static int max(int a, int b) {
return a > b ? a : b;
}
public static int[] toArray(ArrayList<Integer> list) {
int[] arr = new int[list.size()];
for(int i = 0; i < arr.length; ++i)
arr[i] = list.get(i);
return arr;
}
public static ArrayList<Integer> toList(int[] arr) {
ArrayList<Integer> list = new ArrayList<>();
for(int i : arr)
list.add(i);
return list;
}
public static int tournamentKSelection(int[] data, int[] data_copy, int k) {
ArrayList<Integer> winners = new ArrayList<>();
for(int i = 0; i < data.length; i += 2) {
winners.add(max(data[i], data[i + 1]));
}
if(k > 1 && winners.size() == 1) {
for(int i = 0; i < data_copy.length; i++)
if(data_copy[i] == winners.get(0))
data_copy[i] = -1;
return tournamentKSelection(data_copy, data_copy, --k);
}
if(winners.size() % 2 == 1 && winners.size() != 1) winners.add(-1);
if(winners.size() == 1) return winners.get(0);
return tournamentKSelection(toArray(winners), data_copy, k);
}
}
Now I am going to test it :
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
int[] arr = {9, 10, 8, 7, 6, 500, 4, 3, 2, 1};
System.out.println(TournamentTree.tournamentKSelection(arr,arr,1));
System.out.println(TournamentTree.tournamentKSelection(arr,arr,2));
System.out.println(TournamentTree.tournamentKSelection(arr,arr,3));
}
}
This produces the following results:
500 // ok this is the first largest number
10 // ok this is the second largest number
8 // this is the fourth largest number, not the third
Now let me make the call to System.out.println(TournamentTree.tournamentKSelection(arr,arr,3)); alone without the call to k = 1 and k = 2
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
int[] arr = {9, 10, 8, 7, 6, 500, 4, 3, 2, 1};
System.out.println(TournamentTree.tournamentKSelection(arr,arr,3));
}
}
Now this produces the correct result, which is 9. What's going on ? Individually, the result is correct but when I make previous calls to the same function first the subsequent results are wrong.
The only explanation I can think of at the moment is that something in my TournamentTree class is static that shouldn't be.
Any insight ?
I think you should call your function in this way:
System.out.println(TournamentTree.tournamentKSelection(arr.clone(), arr.clone(), 1));
And I recommend also interesting thread about arrays and passing them to function:
Are arrays passed by value or passed by reference in Java?
In the call TournamentTree.tournamentKSelection(arr,arr,3), you are passing in the same array for both args, so even though you are not changing the array through the second argument, you are changing it by the first. Java uses pass by reference, not pass by value. To maintain the original, you have to make a copy and pass in each, like:
public static void main(String[] args) {
int[] arr = {9, 10, 8, 7, 6, 500, 4, 3, 2, 1};
int[] arr_copy = java.util.Arrays.copyOf(arr, arr.length);
System.out.println(TournamentTree.tournamentKSelection(arr,arr_copy,3));
}
purpose of this program is to determine whether or not the variable value
is found within any block of an array (the size of this array is specified by
a user.)
All I want to do is call this method in a driver file and have the user input
the size/data in each block of the array and then enter a value that the program will look for in the array.
public class PracticeExamQ10
{
//method that recieves int array and int value//
public int search(int[] data, int value)
{
//for loop to search the entire array for value//
for(int i = 0; i < data.length; i++)
{
//if data is found, return the index number of value (spot in the array)//
if(data[i] == value)
return i;
}
//returns -1 if value does not occur in the array data//
return -1;
}
}
I then have this as my driver file;
public class PracticeExamQ10Test
{
public static void main(String[] args)
{
PracticeExamQ10 test = new PracticeExamQ10();
test.search({5, 4, 3, 2, 1}, 5);
}
}
is this even possible or do I have to do this instead?
public class PracticeExamQ10Test
{
public static void main(String[] args)
{
int[] data = {5, 4, 3, 2, 1};
PracticeExamQ10 test = new PracticeExamQ10();
test.search(data, 0);
}
}
test.search(new int[] { 5, 4, 3, 2, 1 }, 0);
I'm trying to make a method that expects an array of int and two int S1 and int S2 as parameters. The integers represent the starting position and the ending position of a subarray within the parameter array. The method returns a new array that contains the elements from the starting position to the ending position.
This is what I have, but it keeps giving me this message:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
at java.lang.System.arraycopy(Native Method)
at testing.subArray(testing.java:14)
at testing.main(testing.java:9)
Here's the code:
public class testing{
public static void main(String args[])
{
int[] firstArray = {8,9,10,11,12,13};
subArray(firstArray, 2, 4);
}
public static void subArray(int[]originalArray, int S1, int S2)
{
int[] copy = new int[3];
System.arraycopy(originalArray, S1, copy, S2, 2);
for (int i = 0; i < copy.length; i++){
System.out.println(copy[i]);}
}
}
Help please! :)
The method returns a new array that contains the elements from the starting position to the ending position.
At present it doesn't return anything (it's a void method). However, you could make use of Arrays.copyOfRange() if you wanted to make your job as easy as possible.
As to your current code, here are some hints:
Why are you always allocating three elements for copy? The size of the array ought to depend on S1 and S2.
The arguments to arraycopy() are completely wrong. Read the relevant part of the Java documentation and figure out what the correct values are.
You'll find that this works much better:
public class testing {
public static final int DEFAULT_LENGTH = 3;
public static void main(String args[]) {
int[] firstArray = {8, 9, 10, 11, 12, 13};
int [] subArray = createSubArray(firstArray, 2, 4);
for (int i = 0; i < subArray.length; i++) {
System.out.println(subArray[i]);
}
}
public static int [] createSubArray(int[] originalArray, int startPosition1, int valuesToCopy) {
int subArrayLength = Math.min((originalArray.length-startPosition1), valuesToCopy);
int [] subArray = new int[subArrayLength];
System.arraycopy(originalArray, startPosition1, subArray, 0, subArrayLength);
return subArray;
}
}