0

Whenever I run my code, it says Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0. I make sure that my I value isn't exceeded but it still says it. Can you guys help me?

I made sure that nothing in my for loop exceeded my I value but it seems to be something else that is triggering the problem.

And by the way, sorry if my formatting is incorrect. This is my first time using stack overflow.

One more thing, my compiler says that the error is in line 17(inside my for loop).

Here's my code:

import java.io.*;
public class Main {
    public static int length1;
    public static String numbers;
    public static String str;
    public static void main(String[] args)throws IOException{
        System.out.println("");
        System.out.println("Hello world!");
        char[] nums = new char[length1];
        BufferedReader br = new BufferedReader(new      InputStreamReader(System.in));
        System.out.println("Type in numbers with spaces in them.");
        numbers = br.readLine();
        System.out.println("");
        for(int i = 0; i < numbers.length(); i++){
            nums[i] = numbers.charAt(i);
            System.out.println(numbers.charAt(i));
        }
        length1 = numbers.length();
    }
}
3
  • 2
    What is the value of length1 at char[] nums = new char[length1];? Commented Feb 19, 2019 at 1:27
  • 2
    nums is a zero-length array because length1 = 0 Commented Feb 19, 2019 at 1:27
  • num is zero length. But you try to set the first element of num (i.e. num[0]) in the first iteration of the for loop. Commented Feb 19, 2019 at 1:35

1 Answer 1

1

so your problem is at this line...

char[] nums = new char[length1];

length1 is does not have a value. Try This...

import java.io.*;

public class Main {
    public static int length1;
    public static String numbers;
    public static String str;

    public static void main(String[] args) throws IOException {
        System.out.println("");
        System.out.println("Hello world!");
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Type in numbers with spaces in them.");
        numbers = br.readLine();
        char[] nums = new char[numbers.length()];
        System.out.println("");
        for (int i = 0; i < numbers.length(); i++) {
            nums[i] = numbers.charAt(i);
            System.out.println(numbers.charAt(i));
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.