Array index out of bounds Error - java

I've been having some trouble with this code I made up, in that I've been getting an ArrayIndexOutofBounds exception error and I have no idea what is going on. What I want my code to produce is a char array of numbers.
Here's the code:
public class testing {
static int k = 2;
public static void main(String args[]) {
int[] numArr = new int[] { 15, 18, 21 };
createChar(numArr, k);
}
public static char[] createChar(int numArr[], int k) {
char[] store = new char[k - 1];
for (int i = 0; i < k; i++) {
int divide = numArr[i] / 4;
int numStore = divide % 4;
charN(numStore, store, k);
}
return store;
}
public static char[] charN(int numStore, char store[], int k) {
for (int i = 0; i < k; i++) {
if (k == 0) {
} else {
store[k - 1] = (char) numStore;
k = k - 1;
}
}
System.out.print(store);
return store;
}
}
Thanks a lot!

As the error suggests, it is due to access outside the bounds of the array. ie. some bad index access on an array.
char[] store = new char[k - 1];
You are creating a store character array of size k-1
and passing k as size to charN()
charN(numStore, store, k);
To resolve your problem.
change store declaration as below
char[] store = new char[k];
Also, in class Testing, k must be 3, not 2. where k is the size of the array.
static int k = 3;
When size of the array is k, the indices of array run from 0 to k-1

For value k = 2, the below statement: -
char[] store = new char[k - 1];
creates an array of size 1. So, you can only access its 0th index.
But, further in the charN method, you are accessing it's 1st index at: -
store[k - 1] = (char) numStore; // Since k = 2, k - 1 = 1.
Change your array creation to: -
char[] store = new char[k];
Furthermore, I don't understand why you took k = 2 on first place. May be you meant it to be used as index, in which case, your array creation would be of size k + 1. And accordingly, your for loop will iterate till k + 1, rather than k.
Also, I don't understand the role of your charN method. In fact, tt seems strange that first you are iterating over your array in createChar method, and then passing each element to charN method. And then there also you are iterating over the char array, assigning the same value to multiple index. Apart from that, you are decrementing k and incrementing i at the same time in the loop. That is really strange. And at the end, you are returning your array from both of your methods, but are not using the return value at all.
It's quite hard to understand what you want to do. But you should consider all the points I stated in the previous paragraph. For each step there, think of why you want to do this? Is there any alternative, which might be easy? Do, I really need to methods with 2 iteration here?
I suggest you to take a look at your design once again. The solution which I posted above might solve your compiler error, but there is some problem with your logic. You need to take care of that.

As per your post the statement
char[] store = new char[k - 1];
results in a char array of size 1.
So in charN method when you try to access the
store[k - 1] = (char) numStore;
you are trying to access store[1] as 'k' is 2 here. Which is wrong. because with store[1] you are trying to access the second element in the array where as the array size is only 1.

Related

Delete the highest number of an array

First I created a random array then I decided to create another array to save the number except the highest. I got the prob when printing the array removed the highest number. I assume the issue when assigning item in b but I can't figure out. Please help :<
public static int[] deleteHighestNum(int a[]) {
int b[] = new int[a.length - 1];
for (int i = 0, j = 0; i < a.length; i++) {
if (a[i] > a[j]) {
b[j++] = a[j];
}
}
return b;
you first create a copy of the array with the .clone() method. This will be the second array you created. then you create an int x or something of this sort and set it equal to 0.
start now by iterating the array. if the number is greater then your int, replace the int.
once it is done, make another loop, that checks each value of your second array and if a number is equal to your int, delete it. done.

Two sum - Doesn't work

Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Consider input [3,2,4] and target is 6. I added (3,0) and (2,1) to the map and when I come to 4 and calculate value as 6 - 4 as 2 and when I check if 2 is a key present in map or not, it does not go in if loop.
I should get output as [1,2] which are the indices for 2 and 4 respectively
public int[] twoSum(int[] nums, int target) {
int len = nums.length;
int[] arr = new int[2];
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i = 0;i < len; i++)
{
int value = nums[i] - target;
if(map.containsKey(value))
{
System.out.println("Hello");
arr[0] = value;
arr[1] = map.get(value);
return arr;
}
else
{
map.put(nums[i],i);
}
}
return null;
}
I don't get where the problem is, please help me out
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice. Consider input [3,2,4] and target is 6. I added (3,0) and (2,1) to the map and when I come to 4 and calculate value as 6 - 4 as 2 and when I check if 2 is a key present in map or not, it does not go in if loop.
Okay, let's take a step back for a second.
You have a list of values, [3,2,4]. You need to know which two will add up 6, well, by looking at it we know that the answer should be [1,2] (values 2 and 4)
The question now is, how do you do that programmatically
The solution is (to be honest), very simple, you need two loops, this allows you to compare each element in the list with every other element in the list
for (int outter = 0; outter < values.length; outter++) {
int outterValue = values[outter];
for (int inner = 0; inner < values.length; inner++) {
if (inner != outter) { // Don't want to compare the same index
int innerValue = values[inner];
if (innerValue + outterValue == targetValue) {
// The outter and inner indices now form the answer
}
}
}
}
While not highly efficient (yes, it would be easy to optimise the inner loop, but given the OP's current attempt, I forewent it), this is VERY simple example of how you might achieve what is actually a very common problem
int value = nums[i] - target;
Your subtraction is backwards, as nums[i] is probably smaller than target. So value is getting set to a negative number. The following would be better:
int value = target - nums[i];
(Fixing this won't fix your whole program, but it explains why you're getting the behavior that you are.)
This code for twoSum might help you. For the inputs of integer array, it will return the indices of the array if the sum of the values = target.
public static int[] twoSum(int[] nums, int target) {
int[] indices = new int[2];
outerloop:
for(int i = 0; i < nums.length; i++){
for(int j = 0; j < nums.length; j++){
if((nums[i]+nums[j]) == target){
indices[0] = i;
indices[1] = j;
break outerloop;
}
}
}
return indices;
}
You can call the function using
int[] num = {1,2,3};
int[] out = twoSum(num,4);
System.out.println(out[0]);
System.out.println(out[1]);
Output:
0
2
You should update the way you compute for the value as follows:
int value = target - nums[i];
You can also check this video if you want to better visualize it. It includes Brute force and Linear approach:

Given an integer "n", return an array of size "n" that contains the numbers 0, 1, 2, 3, ...?

My code so far:
public int[] arrayCreation1(int n) {
int[] a = new int[0];{}
int i = 0;
for (int i = 0) i<size.length) i++); {
}
return i;
}
How would I go about completing this?
the variable i is defined twice. If the variable "i" is for the for loop, you can initialise the variable in the loop itself just like you did "int i = 0".
the question stated that you are trying to fill in array with integers starting from 0 to n. You have accept a console input or hard code the value n.
Look up array initialisation and how to assign values.
I think this should get you started atleast.
I am new to programming too and this is what I felt was wrong.
As the comments have stated, your code has many issues:
You are defining a as an array of length 0
You define i as 0 twice
Your for loop is malformed
You have a semicolon after your for loop, which is seen as an empty stament and will prevent the loop from iterating over the block.
Size is not defined anywhere
You return i, which is an int not an array
Here's some code that will work, but I suggest you spend some time with a book or tutorial:
public int[] createArray(int n){
int[] out = new int[n];
for(int i = 0; i < n; i++){
out[i] = i;
}
return out;
}

finding sums in 2 dimentional arrays java

A project I am doing requires me to find horizontal and vertical sums in 2 dimensional arrays. So pretty much its a word search (not using diagonals) but instead of finding words, the program looks for adjacent numbers that add up to int sumToFind. The code below is what I have come up with so far to find horizontal sums, and we are supposed to implement a public static int[][] verticalSums as well. Since I have not yet completed the program I was wondering, first of all, if what I have will work and, secondly, how the array verticalSums will differ from the code below. Thank you
public static int[][] horizontalSums(int[][] a, int sumToFind) {
int i;
int start;
int sum = 0;
int copy;
int [][] b = new int [a[0].length] [a.length];
for (int row = 0; row < a.length; row++) {
for ( start = 0; start < a.length; start++) {
i = start;
sum = i;
do {
i++;
sum = sum + a[row][start];
}
while (sum < sumToFind);
if(sum == sumToFind) {
for (copy = start; copy <= i; copy++) {
b[copy] = a[copy];
}
}
for (i = 0; i < a[0].length; i++) {
if (b[row][i] != a[row][i])
b[row][i] = 0;
}
}
}
return b;
}
Your code won't work.... (and your question is "if what I have will work?" so this is your answer).
You declare the int[][] b array as new int [a[0].length] [a.length] but I think you mean: new int [a.length] [a[0].length] because you base the row variable off a.length, and later use a[row][i].
So, if your array is 'rectangular' rather than square, you will have index-out-of-bounds problems on your b array.
Your comments are non-existent, and that makes your question/code hard to read.
Also, you have the following problems:
you set sum = i where i = start and start is the index in the array, not the array value. So, your sum will never be right because you are summing the index, not the array value.
in the do..while loop you increment i++ but you keep using sum = sum + a[row][start] so you just keep adding the value to itself, not the 'next' value.
At this point it is obvious that your code is horribly broken.
You need to get friendly with someone who can show you how the debugger works, and you can step through your problems in a more contained way.
Test is very simple
public static void main(String[] args) {
int[][] a = {{1, 2}, {1, 0}};
int[][] result = Stos.horizontalSums(a, 1);
System.out.println(Arrays.deepToString(result));
}
Result
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
When you fix this problem, then this should print something like this
[[1, 2], [1, 0]]

Add element into array java

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;
}
}

Categories

Resources