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.
Related
I'm trying to get a program to work where I generate 1,000,000 random numbers between 0 and 1 and then find and print the largest number.
I've got the generator to work and managed to insert each double generated into an ArrayList but I cannot seem to figure out how to find the largest number in the list. At the moment the current code throws the error "java.lang.IndexOutOfBoundsException".
This is all probably due to me being new to the ArrayList and not being fluent with its commands and how it works but I would really appreciate some help on what I'm doing wrong here as I've been stuck for a while.
import java.util.ArrayList;
import java.util.Random;
public class milran {
public static void main(String[] args) {
Random r = new Random();
ArrayList<Double> myList = new ArrayList<Double>();
for (int i = 1; i<=1000000; i++){
double randomValue = 0.0+(1.0-0.0)*r.nextDouble();
myList.add(randomValue);
}
double max = myList.get(1);
for (int z=2; z<=myList.size(); z++){
double test = myList.get(z);
if (test>max){
max = test;
}
}
System.out.println(max);
}
}
First of all take a look at the docs for java.util.Collections and java.util.ArrayList.
Secondly, the ArrayIndexOutOfBoundsException is being triggered by this...
for (int z=2; z<=myList.size(); z++){
double test = myList.get(z);
...
}
This is because array indexing starts at 0, therefore the last element is myList.size() - 1. In other words, when z = myList.size(), it is out of bounds.
Also, in your first for loop, you are using i = 1; 1 <= 1000000. It makes much more sense to use i = 0; i < 1000000 as you can use i to touch each element in an array (or list).
for( i = 0; i < 1000000; i++ )
{
// do something with myArray[i]
}
Here's what I would do after the values have been inserted...
Sort the array: Collections.sort(myList);
Retrieve the last element: System.out.println( myList.get( myList.size() - 1 ) );
...and that's it.
If you need to implement the actual sort yourself then i'd consider using a primitive double array (double[]) rather than a Collection.
Otherwise, if you are using a collection, you can use a foreach loop.
for( Double d : myList ) // for each Double 'd' in myList
{
// do something with d
}
N.B. Another potential issue with this line in the second loop
double test = myList.get(z);
This automatic conversion from Double (object) to double (primitive) is called unboxing. There will be a performance cost, especially when repeated a million times. In the first loop you are converting the other way (autoboxing) – also a million times.
ArrayList start count its elements from 0. You need to replace myList.get(1) to myList.get(0), int z=2 to int z=1 and z<=myList.size() to z<myList.size().
This line: for (int z=2; z<=myList.size(); z++) { is wrong. It should be for (int z=1; z<myList.size(); z++) {.
This is because arrays and lists are 0 based, so a list of size 2 has 2 elements - index 0 and index 1. Currently you try to index into the element number equal to the size, which does not exist.
Along the same line, myList.get(1); should be myList.get(0);.
This is unrelated to your problem, but this line 0.0+(1.0-0.0)*r.nextDouble(); can be much more easily written as r.nextDouble();. I'm not sure what you were trying to do by doing 0 + 1 - 0.
As others have already pointed out, you have an error in your for-loop condition that causes the index to go out-of-bounds.
One way that you can avoid this in the future is by using Java's for-each loop syntax instead of trying to manage the index yourself.
for (Double test : myList) {
if (test>max){
max = test;
}
}
This syntax makes your intent much clearer than the traditional indexed for syntax and removes a point of potential error (managing the index and the bounds of the list) from your hands.
I'm a new to java.I'm looking to print the contents in the two dimmensional array namely myPoints.However,when i'm printing the code.it is throwing up the following error.
mypoints4
i value is 0
2
i value is 1
5
i value is 2
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
2 at perceptron.main(perceptron.java:37)
import java.util.*;
import java.io.*;
import java.text.*;
import java.math.*;
import java.awt.*;
class perceptron{
public static void main(String[] args){
int[][] myPoints = {{2,3},{4,5},{7,8},{9,10}};
int [][] myplot = {{3,4},{5,6},{5,5},{5,3}};
int sum=0;
int i=0;
System.out.println("mypoints"+myPoints.length);
while(i<=myPoints.length){
System.out.println("i value is"+i);
System.out.println(myPoints[i][i]);
i = i+1;
}
}
}
You need to use nested loops for that.
The reason you get the ArrayIndexOutOfBoundsException is because you're using myPoints[i][i], so when i is 2 it is looking for the third element of the third inner array (ie {7,8}) when it doesn't exist
This is because of while(i<=myPoints.length) need to be while(i<myPoints.length).. In case of array in size 5, your i should be i=0, i=1, i=2, i=3, i=4.. Exclude 5.
Another issue is:
System.out.println(myPoints[i][i]);
should be : System.out.println(myPoints[i][0] + " " + myPoints[i][1]);
Because the second dimensional of youre array is only 2 size.. and not 5
Your condition on the while loop must be "less" not "less or equal".
This is because the array index is zero based and hence the index range is always from 0 to (length - 1).
You're going up to (and including) the length of the outer array. This is an array index out of bounds because the indices of an array of length n are 0 ... (n-1). So trying to access index n is out of bounds.
You're accessing the sub array at index i, which is out of bounds for later sub arrays. This would work for a square matrix (you'd read down the diagonal), but your matrix is 4*2, so myPoints[2][2] is OOB, because you can't access index 2 of the length 2 array {7,8}.
The simplest way to iterate over every element in a 2-D array is to have to have a nested loop, like such:
for(int i = 0; i < myPoints.length; i++){
for(int j = 0; j < myPoints[i].length; j++){
System.out.println(myPoints[i][j]);
}
}
An even more concise way of doing this is by using a for-each loop, which gets rid of indices entirely and just gives you each element in the array, in order:
for(int[] row : myPoints){
for(int val : row){
System.out.println(val);
}
}
An even more concise way is to use the method Arrays.deepToString(...):
System.out.println(Arrays.deepToString(myPoints));
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--) {
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
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.