The error message is - Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
I am passing a 2d array into a method and the multiplying the values inside the array by 2. here is the method below.
it works correctly when I pass in the first array from main but not the second - these are also shown below the method code
does anyone have an idea how to amend this error? I also cannot hard code the loop iterations etc
int setuparray2 [][] = new int [][] {{4, 5},{6, 9} };
int setuparray3 [][] = new int [][] {{4, 6, 3},{-1,9,-5}};
scalarMultiplication(2,setuparray1);
scalarMultiplication(2,setuparray3);
public static void scalarMultiplication( int factor, int[][] a)
{
//creates a new array to hold the multiplied value
int multiplyArray [][] = new int [a.length][a.length];
for(int i = 0; i < a.length; i++)
{
for(int j = 0; j < a[i].length; j++)
{
//multiplys each element in the array by the factor
multiplyArray[i][j] = a[i][j] * factor;
}
}
//prints the array with the results
printArray(multiplyArray);
}
when creating multiplyArray you do not reserve enough space.
Instead of:
int multiplyArray [][] = new int [a.length][a.length];
Write:
int multiplyArray [][] = new int [a.length][a[0].length];
You are initializing it in wrong way, below should be the correct way
int multiplyArray [][] = new int [2][3];
Related
This is how it should work, i Put in put for the 1 st array like: 2 3 1 2 3 4 5 6 then 2 and 3 are row and colum and the rest are the values. Problem is the 1st array work, but when i reach EOF ( ctrl+z) then there is out of bound exception. Which mean i cant input value for the 2nd Array like the 1st one. I know there is anotherway where that i can declare array size first then value. But how could i fix this f i still want to usr StdIn.readAllInts() ?
public class MatrixMult {
public static void main(String[] args){
System.out.println("First Matrix Config");
int[] einGabeMatrix1= StdIn.readAllInts();
int zeileM1 = einGabeMatrix1[0];
int spalteM1 = einGabeMatrix1[1];
int[][] ersteMatrix= new int [zeileM1][spalteM1];
int k=2;
int sum;
for(int i=0;i<zeileM1-1;i++){
for(int j=0;j<spalteM1-1;j++){
ersteMatrix[i][j]=einGabeMatrix1[k];
k++;
}
}
System.out.println("Second Matrix Config");
int[] einGabeMatrix2 = StdIn.readAllInts();
int zeileM2 = einGabeMatrix2[0];
int spalteM2 = einGabeMatrix2[1];
int h=2;
int[][] zweiteMatrix= new int [zeileM2][spalteM2];
for(int m=0;m<zeileM2-1;m++){
for(int n=0;n<spalteM2-1;n++){
zweiteMatrix[m][n]=einGabeMatrix2[h];
h++;
}
}
int[][] ergebnisMatrix= new int [zeileM1][spalteM2];
for (int t = 0; t < zeileM1; t++) {
for (int c = 0; c < spalteM2; c++) {
sum = 0;
for (int d = 0; d < spalteM1; d++) {
sum = sum + ersteMatrix[t][d] * zweiteMatrix[d][c];
}
ergebnisMatrix[t][c] = sum;
}
}
for(int i=0;i<zeileM1;i++){
for(int j=0;j<spalteM1;j++){
System.out.println(ergebnisMatrix[i][j]);
}
}
}
}
// This is StdIn.readAllInts(), standard method by java.
public static int[] readAllInts() {
String[] fields = readAllStrings();
int[] vals = new int[fields.length];
for (int i = 0; i < fields.length; i++)
vals[i] = Integer.parseInt(fields[i]);
return vals;
}
It looks like the issue is coming from the fact that StdIn.readAllInts() reads until the EOF. There will be no values left to read by the time your code gets to the second call.
I would suggest instead using the StdIn.readInt() call to read each integer one at a time and then you can use it within your loop to read the exact number of values your need.
Here is an example of how you could get the first 2 integers to find your matrix size:
int zeileM1 = StdIn.readInt();
int spalteM1 = StdIn.readInt();
You will also need to apply this method in your for loops to read the data into the matrix.
I am trying to typecast an integer array into a long array, but I don't quite know how to go about doing this.
So far, my code looks like this:
import java.util.Random;
public class main {
public static int[] sect(){
int[] returned = new int[4];
Random rand = new Random();
returned[0] = 4;
returned[1] = rand.nextInt(8) + 1;
returned[2] = rand.nextInt(7) + 1;
returned[3] = rand.nextInt(6) + 1;
return returned;
}
public static String num(){
for (int j = 0; j < 4; j++) {
int[] ints = sect();
for(int i =0; i < ints.length; i++) {
System.out.print(ints[i]);
}
}
return null;
}
}
I have tried doing things like:
return ((long)num());
But that never works. Does anyone know how I would go about doing this?
Are you using Java 8, if so this will work:
int[] arrayOfIntegers = {1, 2, 3, 4, 5, 6};
long[] arrayOfLongs = Arrays.stream(arrayOfIntegers).mapToLong(i -> i).toArray();
You can't do that.
You simply have to create an equal sized array, and copy the int values into that array. Unfortunately System.arraycopy() can not do that for you... So you can't avoid the manual copying here.
Because an array of int isn't an array of longs. Therefore there is no such cast as from a single int into a single long.
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 6 years ago.
I'm trying to get a sub-array from double[][] 3x3 matrices (to calculate a determinant). I keep getting the ArrayIndexOutOfBoundsException.
Any idea why ?
public double[][] get2DSubArray(double[][] largeArray, int rowStartIndex, int rowEndIndex, int columnStartIndex, int columnEndIndex) {
double[][] subArray = new double[rowEndIndex-rowStartIndex+1][columnEndIndex-columnStartIndex+1];
for (int row = rowStartIndex; row < rowEndIndex; row++) {
subArray[row] = Arrays.copyOfRange(largeArray[row], columnStartIndex, columnEndIndex);
}
return subArray;
}
Looks like it has something to do with array initialization, the array passed to the method does not seem to be 3x3. E.g, following does not produce an Exception:
public static void main(String[] args) throws IOException {
double[][] array = new double[][]{{1d,1d,1d},{2d,2d,2d},{3d,3d,3d}};
double[][] subArray = get2DSubArray(array, 1, 2, 1, 2);
for(double[] arrayElement : subArray){
for(double number : arrayElement){
System.out.println(number);
}
}
}
public static double[][] get2DSubArray(double[][] largeArray, int rowStartIndex, int rowEndIndex, int columnStartIndex,
int columnEndIndex) {
double[][] subArray = new double[rowEndIndex - rowStartIndex + 1][columnEndIndex - columnStartIndex + 1];
for (int row = rowStartIndex; row < rowEndIndex; row++) {
subArray[row] = Arrays.copyOfRange(largeArray[row], columnStartIndex, columnEndIndex);
}
return subArray;
}
Update
Although the above solution does not produce an Exception, it does not produce correct output as well. Mainly because of the following reasons:
Third argument for Arrays.copyOfRange method is exclusive, so we have to pass columnEndIndex+1 for it to work
for loop only executes once for provided set of arguments whereas it should execute at least twice
Instead of assigning Arrays.copyOfRange to subArray[row], we need to assign it to subArray[<zero based index>]
Below solution does work:
public double[][] get2DSubArray(double[][] largeArray, int rowStartIndex, int rowEndIndex, int columnStartIndex,
int columnEndIndex) {
double[][] subArray = new double[rowEndIndex - rowStartIndex + 1][columnEndIndex - columnStartIndex + 1];
int index = 0;
for (int row = rowStartIndex; row <= rowEndIndex; row++) {
subArray[index++] = Arrays.copyOfRange(largeArray[row], columnStartIndex, columnEndIndex+1);
}
return subArray;
}
If the row start was 500 and the end was 505, the variable in the for loop would start at 500 instead of 0. You want to replace "subArray[row] =" with "subArray[row-rowStartIndex] =". You are referencing where it would of been in the larger array compared to where the copy will be in the smaller array.
Edit:
//Fixed Version:
public static double[][] get2DSubArray(double[][] largeArray, int rowStartIndex, int rowEndIndex, int columnStartIndex,
int columnEndIndex) {
double[][] subArray = new double[rowEndIndex - rowStartIndex + 1][columnEndIndex - columnStartIndex + 1];
for (int row = rowStartIndex; row <= rowEndIndex; row++) {
subArray[row-rowStartIndex] = Arrays.copyOfRange(largeArray[row], columnStartIndex, columnEndIndex+1);
}
return subArray;
}
So i am creating a method that basically gives all possible positive integer solutions to the problem x+y+z+w = 13. Really I have designed a program that can get all possible positive integer solutions to any number using any number of variables. I have managed to obtain the solution using this method:
public class Choose {
public static ArrayList<int[]> values;
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] loops = new int[3];
int q = 0;
values = new ArrayList<int[]>();
int[] array = new int[4];
System.out.println(choose(12,3));
NestedLoops(3,10,0,loops,13,array, 0);
for(int i = 0; i < values.size(); i++){
printArray(values.get(i));
}
}
public static void NestedLoops(int n, int k, int j,
int[] loops, int q, int[] array, int g){
if(j==n){
for(int i = 0; i< n; i++){
q-=loops[i];
}
if(q>0){
for(int i = 0; i < n; i++){
array[i] = loops[i];
}
array[n] = q;
values.add(array);
}
return;
}
for(int count = 1; count <= k; count++){
loops[j] = count;
NestedLoops(n,k,j+1,loops, 13, array, g);
}
}
}
My problem is that when i go to print the ArrayList, all i get is the last value repeated again and again. When i try to just print out the values instead of storing them in the ArrayList it works totally fine. This makes me think that the problem is with the values.add(array); line but i don't know how to fix it or what i am doing wrong. Thanks for any help offered.
Try using:
values.add(array.clone());
Every add of the same array just points to that array object. As you keep changing the same object, the final state is what is being shown for all stored elements. The print works as it just dumps the state of the array at that particular instant.
i have integer a = 4 and array b 7,8,9,4,3,4,4,2,1
i have to write a method that removes int ALL a from array b
desired result 7,8,9,3,2,1
This is what I have so far,
public static int[] removeTwo (int x, int[] array3)
{
int counter = 0;
boolean[] barray = new boolean [array3.length];
for (int k=0; k<array3.length; k++)
{
barray[k] = (x == array3[k]);
counter++;
}
int[] array4 = new int [array3.length - counter];
int num = 0;
for (int j=0; j<array3.length; j++)
{
if(barray[j] == false)
{
array4[num] = array3[j];
num++;
}
}
return array4;
I get this error
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Utility.removeTwo(Utility.java:50)
at Utility.main(Utility.java:18)
Java Result: 1
Any help would be much appreciated!
The error stems from this for loop:
for (int k=0; k<array3.length; k++)
{
barray[k] = (x == array3[k]);
counter++;
}
when you create int[] array4 = new int [array3.length - counter]; you are creating an array with size 0. You should only increment the counter if the item is the desired item to remove:
for (int k=0; k<array3.length; k++)
{
boolean b = (x == array3[k]);
barray[k] = b;
if(b) {
counter++;
}
}
To answer your question in the comment, the method should be called and can be checked like this:
public static void main(String[] args) {
int[] array3 = {0,1,3,2,3,0,3,1};
int x = 3;
int[] result = removeTwo(x, array3);
for (int n : result) {
System.out.print(""+ n + " ");
}
}
On this line:
int[] array4 = new int [array3.length - counter];
You create an array with size 0, as counter is equal to array3.length at this point.
This means that you cannot access any index in that array.
You are creating
int[] array4 = new int [array3.length - counter];// 0 length array.
you can't have 0th index there. At least length should 1 to have 0th index.
BTW my suggestion, it is better to use List. Then you can do this easy.
Really an Array is the wrong tool for the job, since quite apart from anything else you will end up with stray values at the end that you cannot remove. Just use an ArrayList and that provides a removeAll() method to do what you need. If you really need arrays you can even do:
List<Integer> list = new ArrayList(Arrays.asList(array))
list.removeAll(4);
array = list.toArray();
(Exact method names/parameters may need tweaking as that is all from memory).
the simplest way is to work with a second array where you put in the correct values
something likte that
public static int[] removeTwo (int x, int[] array3)
{
int counter = 0;
int[] array4 = new int[array3.lenght];
for (int i = 0; i < array3.lenght; i ++) {
if(array3[i] == x){
array4[counter] = array3[i];
}
}
return array4;
}
anoterh way is to remove the x calue from the array3 and shift the values behind forward
The best way to remove element from array is to use List with Iterator. Try,
Integer[] array = {7, 8, 9, 4, 3, 4, 4, 2, 1};
List<Integer> list = new ArrayList(Arrays.asList(array));
for(Iterator<Integer> it=list.iterator();it.hasNext();){
if(it.next()==4){
it.remove();
}
}