On the line with the "here" comment I get an index out of bounds error for some input data. It does not always occur. It does not occur when the program is run on my machine, even. It occurs when a project teammate runs the project on his laptop.
I know there's output from the exception regarding the actual index, but for reasons I don't have that information right now. I might be able to update with the full exception soon.
public int getDistance(int[] arrayA, int[] arrayB) {
int[][] array = new int[arrayA.length][arrayB.length];
for (int i = 0; i < arrayA.length; i++)
array[i][0] = i;
for (int i = 0; i < arrayB.length; i++)
array[0][i] = i; // Here
I cut the method off here as the remainder shouldn't be relevant.
As you can see I create a two dimensional array from two single dimensional arrays (arrayA and arrayB) and the width and height of that array equals the length of the two single dimensional arrays. Then I set the "leftmost" column to incrementing numbers and the "uppermost" row to incrementing numnbers.
If you need more code, I can post it.
When at least one of the array's lenght is 0 then it throws ArrayIndexOutOfBoundsException. Try for example:
int[] arrayA = new int[4];
int[] arrayB = new int[0];
getDistance(arrayA, arrayB);
my guess is that the exception occurs when one of the lists is of length 0, ie. lets say arrayA is the problem and has length=0, you then create array [0][arrayB.length] and when you then try to call array[0][i] it cant access element 0 and throws an OutofBoundsException
Related
I'm learning java and was told arrays are implemented as objects. But they show two different codes without diving into details.
First they ask us to use arrays like this, but the downside is to manually add the values:
int nums[] = new int[10];
nums[0] = 99;
nums[1] = -622;
.
.
.
Then they use this in some programs saying new is not needed because Java automatically does stuff:
int nums[] = {99, - 10, 100123, 18, - 972 ......}
If the second code is shorter and allows me to use arrays straightaway whats the point of the first code if they do the same thing but the first one require more code to input value by hand.
Let's say you were initializing an array of 1 million values, would you use the second method? No, because you would have a huge java file.
The first method is essentially allocating space:
int[] array = new int[1000000];
Creates 1 million spaces in memory with default value 0. Now if you want to initialize them, you may use a loop:
for (int i = 0; i < array.length; i++) {
array[i] = i;
}
If you wanted an array of 10 million values, you only change one number:
// Just add a 0 to 1000000
int[] array = new int[10000000]
Now, if the size of your array changes, you don't have to change the loop. But if you used the second method and wanted an array of 10 million values, you would have to add 9 million values, and 9 million commas to your java file - not scalable.
int[] array = {1, 2, 3, 4, ... 1000000};
The second method is not "scalable." It only works for small arrays where you can confidently assume that the default values of that array won't change. Otherwise, it makes A LOT more sense to use the first (more common) method.
//This is one way of declaring and initializing an array with a pre-defined size first
int nums[] = new int[10];
//This is initializing the array with a value at index 0
nums[0] = 99;
//This is initializing the array with a value at index 1 and likewise allocating rest of array index values
nums[1] = -622;
//This is another way of declaring and initializing an array directly with pre-defined values. Here if you see instead of declaring array size first, directly the values are initialized for it
int nums[] = {99, - 10, 100123, 18, - 972 ......}
It depends on the way you prefer to use the arrays, but you must remember that whenever you use "new" keyword, there is a new space or resource created every time in memory.
When you don't know the items of array at the time of array declaration, then prefer method-1,
and,
when you know the all the values of array at the time of array declaration, then go for method-2
Imagine you want to generate a series of random integers at runtime and want to store in the array:
int[] array = new int[1000000];
Random r = new Random();
for (int i = 0; i < array.length; i++)
array[i] = r.nextInt();
Warning: I am very new to Java and programming in general. I'll try to be as clear as possible.
I am attempting to take a simple integer (inputnumber), convert it to a string (temp), create a new int[] array (numberarray), and loop through this int[] array, starting from the last digit, and print out the name of the digit.
I am rather sure that the conversion from integer to String to int[] array was functional due to Eclipse debugging, but am stumped as to why I am getting an ArrayOutOfBounds message from Eclipse for such a simple for loop. Any clues as to what I am doing wrong is appreciated.
String temp = inputnumber.toString();
int[] numberarray = new int[temp.length()];
for (int i=0;i<temp.length();i++) {
numberarray[i] = temp.charAt(i);
}
for (int i=temp.length();i>0;i--) {
if (numberarray[i]==1) System.out.print("one.");
if (numberarray[i]==2) System.out.print("two.");
if (numberarray[i]==3) System.out.print("three.");
if (numberarray[i]==4) System.out.print("four.");
if (numberarray[i]==5) System.out.print("five.");
if (numberarray[i]==6) System.out.print("six.");
if (numberarray[i]==7) System.out.print("seven.");
if (numberarray[i]==8) System.out.print("eight.");
if (numberarray[i]==9) System.out.print("nine.");
if (numberarray[i]==0) System.out.print("zero");
}
The Eclipse error message I am getting is:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at jt.Intermediate8.main(Intermediate8.java:44)
Arrays are 0-indexed in Java. This means the last value is at index NUMBER_OF_ELEMENTS - 1
Therefore, in your for loop, you should change
int i=temp.length() // this is last index + 1 (since we are starting from 0)
To:
int i=temp.length() - 1 // this is last index
Also, as #brso05 said, don't forget to change your loop-ending condition to i>=0 since the last value going backwards will be at index 0.
Your for loop:
for (int i = temp.length(); i >= 0; i--)
You're starting the loop at temp.length(). That's not a valid index. Perhaps you want temp.length()-1?
You should be doing temp.length() - 1. The reason is that the array starts with index 0 not 1 so the last element in an array is stored at the length - 1. If there are 10 elements then 0-9 are your indexes. Also change i>0 to i>=0 if you want to hit all elements.
for (int i=(temp.length() - 1);i>=0;i--) {
I was reading this post on Stack overflow: copy a 2d array in java and I am a little confused on how the clone method works here...
public int[][] CopyMap(int[][] Map)
{
int [][] copy = new int[Map.length][];
for(int i = 0; i < Map.length; i++)
copy[i] = Map[i].clone();
return copy;
}
I know how to copy using enhanced for loops but I would like to fully understand this way.
1) Why do we put the Map.length in the first set of square brackets but not Map[0].length in the second set of square brackets for int[][] copy = new int[Map.length][];? Don't we have to initialize the length of the columns as well? I'm guessing that we can't clone a 2D array but we can clone a row or column at a time.
2) By cloning the columns one column at a time and putting it into our 2D array it sets the length of the columns for us?
3) Could we reverse this code by doing this
public int[][] CopyMap(int[][] Map)
{
int [][] copy = new int[][Map[0].length];
for(int i = 0; i < Map[0].length; i++)
copy[i] = Map[i].clone();
return copy;
}
4) Also copy[i] ? This is a 2D array, so shouldn't it be copy[i][] ? Or something like that.
In Java a 2D array is essentially an array of arrays (possibly with different lengths). It is important to remember this. For example, this is OK:
int[][] ar = new int[2][];
ar[0] = new int[8]; // ar[0][0..7]
ar[1] = new int[4]; // ar[1][0..3]
The syntax new int[8][10] can be used as a convenience to create 8 separate arrays of 10 elements each.
If you are familiar with C: an int[][] in Java is more similar to an int** in C.
Note: Map is a terrible name for a variable in Java; variable names generally start with lowercase letters and there is also a very common base container interface of the same name.
1) Why do we put the Map.length in the first set of square brackets but not Map[0].length in the second set of square brackets for int [][] copy = new int[Map.length][]; ?
Because we are starting with an array of Map.length int[]'s, and then cloning those int[]s one at a time.
Don't we have to initialize the length of the columns as well?
No, because when we go through each int[] in Map, we just use clone() to copy it: copy[i] = Map[i].clone().
By cloning the columns one column at a time and putting it into our 2D array it sets the length of the columns for us?
A "column" is just a concept you made up that is only relevant to tabular data (column-major tabular data in your specific context). Anyways, "setting the length" isn't exactly accurate because it implied that something whose length is being set existed in the first place; but when you do int x[][] = new x[5][], x[0] is null until you assign it to something. By cloning the int[]s one at a time, we're just... cloning them one at a time. So, yes, each clone will be the same size as the original.
3) Could we reverse this code by doing this
public int[][] CopyMap(int[][] Map)
{
int [][] copy = new int[][Map[0].length];
for(int i = 0; i < Map[0].length; i++)
copy[i] = Map[i].clone();
return copy;
}
No; and hopefully the reason why is clear now that you know that an int[][] is an array of arrays. The expression new int[][size] doesn't make much sense; it says that we want each int[] in the array to have a given size, but it doesn't say how many int[]s are in the array. It's wrong for the same reason that int[] x = new int[] is wrong.
4) Also copy[i] ? This is a 2D array, so shouldn't it be copy[i][] ? Or something like that.
No, it should be copy[i]. I'll leave figuring out the reasons as an exercise.
So I got this assignment while my teacher is away, and basically I have to make a student project. The student has a name, marks, and average. To calculate the average I decided to store the marks inside a int[] array.
public void addQuiz(int m)
{
int l = (marks.length);
marks[l] = m;
}
int[] marks = new int[8];
But when I run the function:
student.addQuiz(90);
I get:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8
Any help?
I'm not sure what the int[8] part does but it was in the tutorial I followed and it would give me a null pointer without it. There are eight marks in total so I just made it 8.
You can't dynamically add things to an array. You should use an array list instead.
Arraylist<Integer> marks = new ArrayList<Integer>();
then in your addQuiz method:
public void addQuiz(int m) {
marks.add(m)
}
You'll probably also need to change your method for calculating the average a bit, but that should be trivial and I'll leave it to you.
The error says: ArrayIndexOutOfBoundsException: 8
You have an array with 8 elements, indexed from 0 to 7 (inclusive). This array has a length of 8, and you are actually trying to access marks[8], when you only can go up to 7.
In Java, Array index starts from '0'. so, you cannot access the index of the array equal to the length of the array.if your arrays length is '8', then the last index of the array is '7' not '8'. if you are trying to access the illegal index of the array, then ArrayIndexOutOfBoundException is thrown. the code should be changed to
public void addQuiz(int m)
{
int l = (marks.length); //assuming marks is an array of length '8'
marks[l-1] = m; //index is 7 now
}
To calculate the average, you need to sum up the contents of the array (provided all the values are of int values) and then divided by the lenght of the array
int sum = 0;
int avg = 0;
for(int i=0; i<array.length;i++){
sum =sum+array[i];
}
avg = sum/array.length;
Hope this gives an idea
Use Arraylist<Integer> and then you can add to the list dynamically
There is not index in this array for this marks[l] = m;. use marks[l-1] = m;
You can call this for loop in main for getting marks 8 times.
for(int i=0;i<8;i++)
student.addQuiz(<marks you want to enter>, i);
You can define addQuiz function like below
public void addQuiz(int m, int arrayIndex)
{
marks[arrayIndex] = m;
}
int[] marks = new int[8]; //this will be as it is
These are minimal changes. You can make your code better by passing array marks to addQuiz as a parameter. But this will also work, its just that this is not the best way to write code.
I get the output for the program mentioned below. In addition Ii also encounter an exception as:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
at ReverseOrder.main(ReverseOrder.java:15)
Why does this happen?
public class ReverseOrder {
public static void main(String[] args)
{
int anArray[]={1,2,3,4,5,6};
int anotherArray[]=new int[6];
for(int i=5,j=0;i>=0;i--,j++)
{
anotherArray[j]=anArray[i];
}
//System.out.println(anotherArray.length);
//System.out.println(anotherArray[2]);
for(int j=0;j<=anotherArray.length;j++)
{
System.out.println(anotherArray[j]);
}
}
}
Change
for(int j=0;j<=anotherArray.length;j++)
to
for(int j=0;j<anotherArray.length;j++)
Since if it's <= you'll be going out of bounds.
In Java (and most languages), arrays are zero-based. If you have an array of size N then its indexes will be from 0 to N - 1 (total size of N).
The problem is here:
for(int j=0;j<=anotherArray.length;j++)
{
System.out.println(anotherArray[j]);
}
you are accessing a position out of the array. This happen because method length gives you the number of elements in the array, and since the first position of an array is 0 and not 1 you should end the loop on anotherArray.length - 1 and not anotherArray.length.
There are two possible solutions to this where you modify your loop to:
a) for(int j=0;j<=anotherArray.length - 1;j++)or
b)for(int j=0;j<anotherArray.length;j++)
The latter (b) is preferable, since it has less arithmetic operations on it.
change
<=anotherArray.length
to
< anotherArray.length
For example, if array is
int arr[] = new int[2];
arr.length; // it will be 2, which is [0] and [1] so you can't go upto <=length,
// that way you will access [2] which is invalid and so the exception
for(int j=0;j<anotherArray.length;j++)
instead of
for(int j=0;j<=anotherArray.length;j++)
Because arrays are zero-based in Java.
You will get ArrayIndexOutOfBoundsException when you try access the element that's out of Array limit.
for(int j=0;j<anotherArray.length;j++) {
System.out.println(anotherArray[j]);
}
Why do you use this way to reverse your array in first place. Any way
for(int j=0;j<=anotherArray.length;j++) should change to
for(int j=0;j<anotherArray.length;j++)
Consider this too, It is easy.
int anArray[]={1,2,3,4,5,6};
int temp=0;
for (int i=0;i<anArray.length/2;i++){
temp=anArray[i];
anArray[i]=anArray[anArray.length-(1+i)];
anArray[anArray.length-(1+i)]=temp;
}
Now your array is reversed.