Adding each value to an integer array - java

Can you help me with my problem? I need to add values to my int array but all I get is an ArrayIndexOutOfBoundsException.
public static void numberSort(){
int quantity = 0;
int[] values = new int[quantity];
int allocate = 0;
quantity = Integer.parseInt(JOptionPane.showInputDialog("How many values do you wish to sort? : "));
for(int x = 0; x <= values.length; x++){
allocate = Integer.parseInt(JOptionPane.showInputDialog("Values you want to sort : "));
values[allocate] = x;
System.out.println(values[x]);
}

int quantity = 0;
int[] values = new int[quantity];
You're allocating an array with 0 locations, which is effectively a zero-length array. This means that it really doesn't have any valid locations, so you can't store anything into it. This is why you're getting an ArrayIndexOutOfBounds exception when you attempt to store anything inside the array.
You will have to move the line where you allocate values to the line after the line where you read in the value of quantity.
Your next problem is your for loop:
for(int x = 0; x <= values.length; x++)
Array indices run from 0 to array.length - 1. So typically the terminating condition for the for loop is x < values.length. If this was your code, you wouldn't have seen this exception. However, even if you fix this to make quantity a non-zero value, you will get the exception when you attempt to fill the array since values[array.length] is out of bounds. So you will have to change your for loop to:
for(int x = 0; x < values.length; x++)
I also noticed that you have values[allocate] = x;. What you want is values[x] = allocate;, since you want the xth element of the array.

This line is your problem
int quantity = 0;
int[] values = new int[quantity];
You are creating an array with length 0. The length of an array is established when the array is created. After creation, its length is fixed.
Read more in tutorials: Arrays
For quick fix in your code just init your array after quantity
int quantity = Integer.parseInt(JOptionPane.showInputDialog("How many values do you wish to sort? : "));
int[] values = new int[quantity];
And in for loop change <= to < cause arrays starts in 0.
for(int x = 0; x < values.length; x++){
allocate = ...
values[x] = allocate; // you want to allocate in position "x" allocate
}

Aside from creating an array of 0 length, your for loop end condition is incorrect. You wrote x <= values.length, but you should write x < values.length. Since arrays in Java are 0-indexed, that means the valid range of indices are 0 to values.length - 1.

I count three errors in there. The most significant one:
for(int x = 0; x <= values.length; x++){
Java arrays index from zero - that means that for example an array with length of 5 has indexes 0, 1, 2, 3 and 4. Anything beyond that in either direction results in the ArrayIndexOutOfBoundsException. Because you use <=, you read one value beyond what's allowed. Replace it with <.
Also, you initialize your array to size zero. That means you can't really use it. Initialize your array with quantity only once quantity has the correct value!
Finally, I believe you want values[x] = allocate;, not vice versa.

Related

Creating an array with mutable data type

**Initializing an array of NaturalNumbers with values 1 through 4**
When I debug, I find the array = [5,5,5,5] and my goal is that the array = [1,2,3,4].
NaturalNumber[] array = new NaturalNumber[4];
NaturalNumber count = new NaturalNumber2(1);
for (int i = 0; i < array.length; i++) {
array[i] = count;
count.increment();
Here is a link to all the methods that can be used with natural numbers. I just do not understand how can I create the wanted array without changing count's value.
http://web.cse.ohio-state.edu/software/common/doc/index.html?components/naturalnumber/NaturalNumber.html
NaturalNumber[] array = new NaturalNumber[4];
NaturalNumber count = new NaturalNumber2(0);
for (int i = 0; i < array.length; i++) {
count = new NaturalNumber2(i);
count.increment();
array[i] = count;
**Initializing an array of NaturalNumbers with values 1 through 4**
You can do it this way as well
int[] numbers = IntStream.range(1, 5).toArray();
You got 5,5,5,5 because you are using a boxed non-primitive type instead of a primitive.
So references to NaturalNumber count are to the location of an object. When you put that count into the array, you are putting the reference (four copies) and it contains the last value. Since you do an increment as the very last thing in the last go-through the loop, it points to a value 5 (but is not the value 5).
If you declared int count instead and used count++ since you can't call .increment () on a primitive, then you'd get the sequence 1, 2, 3, 4. The run-time engine would put the actual value of count at each time into the array.

i want fix my method to reverse int array

trying to write a method reverseIntArray(int[] array) which should return a reverse copy of an integer array. For example, if array = [1,2,3,4], then the method should return the array [4,3,2,1].
The program compiles without any error messages. What are the errors causing incorrect incorrect behavior of the program at runtime?
public static int[] reverseIntArray(int[] array) {
int[] result = new int[10];
int j = array.length;
for (int i = 1; i < array.length; i++ ) {
result[i] = array[j];
j++;
}
return result;
}
how should the error be corrected?
what exactly is the error?
what effect the error would have?
You need to set j to be array.length -1 instead of array.length and decrement it instead of incrementing it, and start your for loop index at 0 not 1.
There are a couple of issues with your code:
Your result array is being created with a size of 10 rather than the size of the array being passed in. This will cause an issue if you pass in an array with a smaller or larger size than 10. You can resolve this with: int[] result = new int[array.length];
You're initializing i with a value of 1. Java arrays start at index 0, so your loop will skip populating the first element of the array. You instead want: for (int i = 0; i < array.length; i++) {
Because java arrays start at index 0, the last element's index will be 1 less than array's size. You want: int j = array.length - 1;
You want to retrieve array's elements in reverse order, but your code is incrementing j rather than decrementing it. You want j-- where you have j++
To solve array related problem you must know only about its storage in memory and its index.
In your solution you are trying to overwrite values. In your solution you need to make sure that you are saving older value before writing any new value to any index.
NOTE: You must know that how to swap two numbers.
int[] arr={1,2,3,4};
int i=0;
int j=arr.length-1;
while(i<j)
{
//Swapping two numbers
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
i++;
j--;
}
You can also do the same using for loop.

What is the quickest way to arrange numbers to 3 dimensional array?

I need to arrange numbers of a given size (provided by user at runtime), to 3 dimensional array to represent these numbers in real 3D space.
For example if user enters 7 then I need to create an array of size 2,2,2 and arrange the first 7 numbers given by user into the array starting from position 0,0,0 .
The cube should always be smallest possible for example cube of size 2 can contain 2*2*2 = 8 values. And need a function that can take input numbers and return 3D integer array with values inserted from input array (input[0] will become result[0][0][0] and so on).
int input[7] ;
int[][][] result = bestFunction(int[] input) {...}
I have implemented with 3 nested for loops by checking each value at a time.
Is there a better or faster approach to implement it?
Do a Math.floor(Math.cbrt(val)) to get the dimension size.
I think we can reduce it to level 1 nesting, or using two loops, using a string input for the z-axis values.
for(int i = 0; i<size; i++)
for(int j = 0;j<size;j++)
arr[i][j]= Arrays.stream(sc.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
where Scanner sc = new Scanner(System.in); if you're taking in user input.
Three for loops would be O(n) as long as you break right after the last element of the input is put in.
int[][][] func(int[] input) {
int size = (int) Math.ceil(Math.cbrt(input.length));
int[][][] result = new int[size][size][size];
int x = 0;
loop: for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
for (int k = 0; k < size; k++) {
result[i][j][k] = input[x++];
if (x == input.length)
break loop; //Finish processing
}
}
}
return result;
}

Taking data from one array to create another. What's wrong with this loop?

I am working on an assignment where I need to create two arrays, then look through them and create a new array that holds any values inside of both the first two. Originally, I was close to accomplishing this by making an arraylist but my lab professor told me that wasn't allowed so I needed to re-start and didn't have enough time to figure out the solution.
If you'd like to see the whole code I have now: http://pastebin.com/thsYnj2z
I am really struggling with this loop here:
for(int i = 0 ; i < Xarr.length ; i++){
for(int j = 0 ; j < Yarr.length ; j++)
//Compare. If the two are the same, they go inside of A.
if (Xarr[i] == Yarr[j]){
ArrA[k] = Xarr[i];
k++;
System.out.println(ArrA[k]);
break;
}
My output is remaining 0 for my ArrA[k] array. I can't seem to trouble shoot this issue on my own.
try making these changes
for(int i = 0 ; i < Xarr.length ; i++){
for(int j = 0 ; j < Yarr.length ; j++)
//Compare. If the two are the same, they go inside of A.
if (Xarr[i] == Yarr[j]){
ArrA[k] = Xarr[i];
System.out.println(ArrA[k]); // or print them all later
k++;
break; // break to outer loop
}
}
}
note
Assuming OP has correctly initialized ArrA
note2
Assuming that only unique values are required, hence the breaking
Does your solution require that no values are duplicated in ArrA? Or are duplicate values allowed? For example, if some values occur multiple times in each array, you could get multiple matches on the same number.
If duplicates aren't a problem:
for(int i = 0 ; i < Xarr.length ; i++){
for(int j = 0 ; j < Yarr.length ; j++){
//Compare. If the two are the same, they go inside of A.
if (Xarr[i] == Yarr[j]){
ArrA[k] = Xarr[i];
System.out.println(ArrA[k]);
k++;
}
}}
As I understand it, the problem is to take 2 arrays, and produce a third array which is a Union of the first 2. Union of 2 sets being the subset of the values found in both sets.
Your code was missing some braces, so put those back in there. Also you wont want to print the k+1th item after you just put a value in ArrA[k] im assuming.
Otherwise you were pretty much there. The break terminates the inner loop and allows the outer loop to increment i and continue on. This is because you have already found a match, no need to continue searching, just move onto the next index in Xarr.
Algorithm goes like this: For each value in X, search Y for a match. If it is found, add this value to A.
for(int i = 0 ; i < Xarr.length ; i++) {
for(int j = 0 ; j < Yarr.length ; j++) {
//Compare. If the two are the same, they go inside of A.
if (Xarr[i] == Yarr[j]){
ArrA[k] = Xarr[i];
System.out.println(ArrA[k]);
k++; //you probably want to increment k after you add to ArrA, not before
break;
}
}
}
public static void main(String... args){
int[] xArr = {1, 1,1,1,1,1};
int[] yArr = {1, };
int[] kArr = new int[xArr.length > yArr.length ? xArr.length : yArr.length];
int k = 0;
for(int x = 0; x < xArr.length; x++){
for(int y = 0; y < yArr.length; y ++){
int xNum = xArr[x];
int yNum = yArr[y];
if(xNum == yNum) kArr[k++] = xNum;
}
}
int[] resizedKArr = new int[k];
for(int i = 0; i < resizedKArr.length; i++) resizedKArr[i] = kArr[i];
Arrays.sort(resizedKArr);
for(int x : resizedKArr) System.out.println(x);
}
First, xArr and yArr are given some random numbers, and then kArr is initialized with the size of the lagest array we are comparing with to ensure the array has enough space to hold similar values.
Then, in the next section we do a loop inside of a loop to compare the values against each other and if they are similar then k++ and set the next value in the array. This goes on until the loops are completed, notice there really is never a need to break from either loop until all values are compared. At that point the loops break themselves and move on to the next bit of code.
The last section is just to create an array of the same size as k and move the values over, I don't know the requirements of your studies, although when using primitives like this you may want to do this in case you have a matching 0 as a number. Otherwise you'll have a ton of 0s filling the empty spaces of your array.
And lastly, we just sort the array for good measure and print it out.
Hope I've answered your question and you get something out of this post!
The problem is printing ArrA[k] after k++. Try increasing line after print.

Find the maximum of the length of 2 arrays

I am passing 2 arrays to the controller with different lengths, I want to execute a for loop and length of that will be the max of the length of 2 arrays.
I am not getting how to execute that. I tried Math.max but its giving me error as cannot assign a value to the final variable length.
String[] x =0;
x.length = Math.max(y.length,z.length);
for(int i=0; i < x.length; i++)
The no of elements in x and y are not fixed. it changes what we are passing from the front end.
Initialize the new array with the desired length:
String[] x = new String[Math.max(y.length,z.length)];
In case you don't need to create an array, just use the result of Math.max as conditional to stop your loop:
for (int i = 0; i < Math.max(y.length,z.length); i++) {
//...
}
Just bring your Math.max() operation into the array's initialization.
String[] x = new String[Math.max(y.length, z.length)];
Here's an expansion for clarity:
int xLength = Math.max(y.length, z.length);
String[] x = new String[xLength];
Edit: Unless, OP, you're not interested in creating another array...
I want to execute a for loop and length of that will be the max of the length of 2 arrays
Just bring your Math.max() operation into your for loop:
for(int i=0; i < Math.max(y.length, z.length); i++){
//code here
}
Set a variable to the maximum length of the arrays, create a new array with that length and then loop until that point.
int maxLen = Math.max(y.length, x.length);
String[] array = new String[maxLen];
for(int i = 0; i < maxLen; i++){
// Loop code here
}
int max_length = Math.max(y.length,z.length);
for(int i=0; i < max_length ; i++){
//...
}
you can use that max_length to create a new String[] if you are trying to create an array with total length of y and z arrays, like
String[] newArray = new String[max_length];

Categories