Exception in thread ArrayIndex - java

I was doing some beginner programming with series and input but im having the same problem constantly.Cant find the solution.Basically what i want my program to do for now i input a list of numbers and print them out.And im getting the same error over and over whatever i change in program.Here is my code.
import java.util.Scanner;
public class Test437 {
public static void main(String[] args) {
int limit = 25;
int cnt;
int addtion;
double dbt; //Devided by two % 2
Scanner input = new Scanner(System.in);
int [] ya = new int[8];
for(cnt = 0;cnt < ya.length;cnt++)
{
System.out.print("ya[" + cnt + "]= ");
ya[cnt] = input.nextInt();
}
System.out.println(ya[cnt]);
}
}
Im getting this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8
at Test437.main(Test437.java:22)

System.out.println(ya[cnt]); this line is outside loop. Cnt is equal to an array size so it cannot be used in such way because there is no element in the array with such index.

The line:
System.out.println(ya[cnt]);
needs to be in a loop again to print out all the array values after accepting them:
for (cnt = 0;cnt < ya.length;cnt++) {
System.out.println(ya[cnt]);
}
Alternatively, you could do:
System.out.println(Arrays.toString(ya));

cnt condition to leave the loop is to exceed the length therefore you get in indexoutofbounds

This line
System.out.println(ya[cnt]);
is trying to access element at ya.Length index which does not exists.
In your example ya[8] contains elements at position from 0 to 7 (ya[0] ya[1] ... ya[7] and you're trying to access ya[8] bacuase cnt variable is 8 after the for statement ends.
Therefore the compiler throws an indexOutOfBounds exception.

Related

Java Exception : java.lang.ArrayIndexOutOfBoundsException

So for my Ap computer Science class One of my project keep getting java.lang.ArrayIndexOutOfBoundsException: 390000 Its a Sound reverse file
Here is the code:
import sounds.APSoundClip;
import sounds.Sample;
public class ReverseSound {
public static void main(String[] args) {
APSoundClip clip = new APSoundClip("money.wav");
APSoundClip newClip = clip.clone();
int pos = clip.getLength();
int cloned = 0;
for(Sample clipSample : clip) {
clip.getSample(pos); //error is here
int newValue = clipSample.getValue();
newClip.getSample(cloned).setValue(newValue);
pos--;
cloned++;
}
newClip.draw();
}
}
That seems like a "traditional" mistake - you initialize pos with int pos = clip.getLength();
Then at the first iteration you do clip.getSample(pos); - the last element is at index clip.getLength() - 1. You are trying to access the element at position clip.getLength(), that's why you are getting the index out of bounds error.
Java Arrays start with an index of zero, and because of this, their last index will be one less than their length. In your situation, you are assuming that clip.getLength()is the last element in the array, however, when you take a look at the anatomy of the array, it would really be clip.getLength()-1.

print all binary numbers of size n using recursion

i am trying to print all size n binary numbers, for example if size is 3 , i want to print all numbers from 0 to (2^3)-1 in binary form, below if my code implementating, it prints 000 and gives me this error
"Exception in thread "main" java.lang.StackOverflowError
at java.lang.String.getChars(String.java:854)
at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:391)
at java.lang.StringBuilder.append(StringBuilder.java:119)
at java.lang.StringBuilder.<init>(StringBuilder.java:93)
at NBinary.tobinary(NBinary.java:11)
at NBinary.tobinary(NBinary.java:12)".
String temp = str+x; is line 11
tobinary(temp, size); is line 12
below is my code
public class NBinary {
static int arr[] = {0,1};
static void tobinary(String str,int size){
if(str.length() == size){
System.out.println(str);
}
for(int x : arr){
String temp = str+x;
tobinary(temp, size);
}
}
public static void main(String[]args){
tobinary("", 3);
}
}
please help me find the error. thanks
One problem is that you are not giving any Recursion Termination condition.
So the function recurses infinitely. No condition is there to cease the calling.
That is why the stack allocated for the function call runs out of space and you get StackOverflowError.
See more here:
http://docs.oracle.com/javase/7/docs/api/java/lang/StackOverflowError.html
What is a StackOverflowError?

Nullpointer exception java runtime [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
The program looks slightly advanced; it is not. Simple manipulation of array.
The program compiles correctly, however, it encounters an exception run-time.
Exception in thread "main" java.lang.NullPointerException
at Ordliste.leggTilOrd(Tekstanalyse.java:85)
at Tekstanalyse.main(Tekstanalyse.java:23)
So there is something wrong with if(s.equalsIgnoreCase(ordArray[k])).
I cannot see why. It even provides the correct output.
import java.io.File;
import java.util.Scanner;
import java.io.FileNotFoundException;
public class Tekstanalyse {
public static void main(String[] args) throws FileNotFoundException {
Ordliste ol = new Ordliste();
ol.lesBok("scarlet.text");
ol.leggTilOrd("A");
}
}
class Ordliste {
private int i = 0;
private String[] ordArray = new String[100000];
private int antForekomster;
private int arrStorrelse = 0;
public void lesBok(String filnavn) throws FileNotFoundException {
File minFil = new File(filnavn);
Scanner scan = new Scanner(minFil);
while (scan.hasNextLine()) {
ordArray[i] = scan.nextLine();
//System.out.println(ordArray[i]);
i++;
arrStorrelse++;
}
System.out.println("Array size: " + arrStorrelse + " Capacity: " + ordArray.length);
}
public void leggTilOrd(String s) {
for (int k = 0; k < ordArray.length; k++) {
if (s.equalsIgnoreCase(ordArray[k])) {
antForekomster++;
System.out.println("Den har vi sett for!");
} else {
s = ordArray[arrStorrelse];
}
}
}
}
I'm pretty sure the error is right here:
for (int k = 0; k < ordArray.length; k++) {
if (s.equalsIgnoreCase(ordArray[k])) {
antForekomster++;
System.out.println("Den har vi sett for!");
} else {
s = ordArray[arrStorrelse]; // <- dangerous
}
}
As I said in the comment, ordArray could contain null elements if the read text file does not contain 100.000 lines of text. If this is the case, the above line would write null to s because s.equalsIgnoreCase(null) is false.
You should think about using a list instead of an array.
private List<String> ordList = new ArrayList<String>();
(or use a different variable name, it is up to you)
Then you can add new entries to the list using ordList.add(scan.nextLine());. This list won't contain any null elements and your mentioned problem should be gone.
I would highly recommend you to simply use a debugger to debug your code , but here goes:
in your lesBok method you fill your array with strings and make a counter arrStorrelse. to be the amount of elements in the array you made. however the array is filled for indexes 0 to n-1. and arrStorrelse is equal to N you did however allocate space in the array for this. so when in leggTilOrd() you iterate the first time and you enter the else clause you do this
for (int k = 0; k < ordArray.length; k++) {
if (s.equalsIgnoreCase(ordArray[k])) {
antForekomster++;
System.out.println("Den har vi sett for!");
}
else {
int arrStorrelse2=arrStorrelse;
s = ordArray[arrStorrelse];
}
in that else clause s is set to ordArray[arrStorrElse]; however arrStorrElse is at that moment one higher than the last intialised element of your array. so it sets s to the null pointer.
then the next iteration of your loop in the if clause
if (s.equalsIgnoreCase(ordArray[k])) {
antForekomster++;
System.out.println("Den har vi sett for!");
the s.equalsIgnoreCase() call is done on an s that is null that's where the null pointer exception comes from.
you need to change the arrStorrElse assignment you haven't explained what it should do so i can't do that for you also try to learn how to debug your code here is a usefull link:
http://www.tutorialspoint.com/eclipse/eclipse_debugging_program.htm
I have compiled and tested your code.
s.equalsIgnoreCase(null)
throws nullPointerException.
Maybe you should try to use ArrayList instead of Array to avoid iterating through nulls.
It took me some time to figure out why the NullPointerException occurs and I have to agree with Piotr and Tom: The NPE is caused by the line
s.equalsIgnoreCase(ordArray[k])
and a side-effect in your code. This side-effect is introduced by reassigning the parameter s in the else-branch to null (this value comes from ordArray[arrStorrelse]). After this reassignment happened, you will have something like this:
null.equalsIgnoreCase(ordArray[k])
And voila, there is the NullPointerException.

Issues with the following method in java regarding reading from an input file

Hi guys so I keep getting the following error when I try running my program.
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
at Simulation.getJob(Simulation.java:12)
at Simulation.main(Simulation.java:58)
The piece of code I'm working with looks like this:
//all of this is under main.
m = Integer.parseInt( in.nextLine() );
//make sure the file has stuff in it
while(in.hasNext()){
in.useDelimiter("\n");
//Create an array of type job to keep track of our number of jobs.
Job[] jobs = new Job[m];
for(int i = 1; i < m; i++){
jobs[i] = getJob(in);
System.out.println(jobs[i]);
}
}
//getJob function is here:
public static Job getJob(Scanner in){
String[] s = in.nextLine().split(" ");
int a = Integer.parseInt(s[0]);
int d = Integer.parseInt(s[1]);
return new Job(a,d);
}
The data from the in file looks like this
3
2 2
3 4
5 6
The problem is that your code does not match the input format: when the nested for loop is over, the outer while loop takes you back to the beginning of the reading code, and tries to read another set of m items.
To fix this, simply remove your outer loop:
in.useDelimiter("\n");
//Create an array of type job to keep track of our number of jobs.
Job[] jobs = new Job[m];
for(int i = 0; i < m; i++){
jobs[i] = getJob(in);
System.out.println(jobs[i]);
}
Note that the loop index i needs to start at zero, not at 1, because Java arrays are zero-based.

Java 1.4.2 - ArrayIndexOutOfBounds Error [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
(I am using Java 1.4.2) I wanted to have an array that should flip a 'coin' a certain amount of times given by the user (the coin can flip up to 1000 times). Then randomly generate an integer between 1 and ten, store all the numbers in an array. I have the following code but it keeps on giving me the following error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
at CoinFlip.main(CoinFlip.java:42)
Here is the code I wrote.
import java.io.*;
import java.math.*;
public class CoinFlip
{
public static void main(String[] args) throws IOException
{
// setting up variables
String timesString;
int times;
// setting up input
BufferedReader in;
in = new BufferedReader(new InputStreamReader(System.in));
do
{
// times will display how many times the coin will flip
// loop if times does not fulfill the requirements
System.out.println("How many times do you want the coin to flip? (MUST be an integer between 1 to 1000)");
timesString = in.readLine();
// convert timesString into an integer
times = Integer.valueOf(timesString).intValue();
if((times > 1000)||(times < 1))
{
System.out.println("ERROR: The number of times you flip the coin must be an integer between 1 and 1000.");
}
System.out.println("The value for times is " +times);
}
while((times > 1000)||(times < 1));
// create a new array
double flip[] = new double[times];
// create a new variable timeStore that sets the boolean conditions for the For Loop
int timeStore;
for(timeStore = 0; timeStore <= times-1; timeStore++)
{
System.out.println("timeStore (how many iterations) is " +timeStore);
System.out.println("FOR LOOP: When " +timeStore+ " is less than or equal to " +(times-1));
flip[times] = Math.round(Math.random()*9)+1;
// the line above stores a random integer between 1 and 10 within the current index
System.out.println("flip["+times+"] = "+flip[times]);
}
}
}
At line 42;
flip[times] = Math.round(Math.random()*9)+1;
Should be;
flip[timeStore] = Math.round(Math.random()*9)+1;
Then also in the System.out on line 44.
These are wrong:
42: flip[times] = Math.round(Math. random()* 9 ) + 1;
44: System.out.println("flip[" + times + "] = " + flip[times]);
It appears you meant
42: flip[timeStore] = Math.round(Math.random()*9)+1;
44: System.out.println("flip["+timeStore+"] = "+flip[timeStore]);
Since you declared flip as an array of size times, only indices 0...(times - 1) are valid. In particular, index times is invalid and so flip[times] will throw.
Note that the compiler was telling you the offending line, and the offending index passed in. It's telling you you passed in 7 as the index. But note, this exception is happening on the first iteration of your loop. You can tell this by the output that your program would have produced since you have helpful print debugging statements in your code. Thus, you should have been able to reason: hey, why is my array seeing the index 7 on the first iteration of the loop when the index should be 0? At that point, the error practically figures itself out.
Also, idiomatic usage of arrays is:
for(timeStore = 0; timeStore < times; timeStore++)
but even better is:
for(timeStore = 0; timeStore < flip.length; timeStore++)

Categories

Resources