-2

I'm trying to take user input and put it into a character array and then print it out.... It's part of a bigger program and since i'm a new coder, I was hoping if you could keep the program simple without.... I get the error "Array index out of bounds". I tried changing the length of the array but that still didn't work.

public static void main(String[] args) {
        // TODO Auto-generated method stub


        char[] ToEdit = new char [];

        Scanner sc = new Scanner(System.in);
        for (int i=0; i<5; i++)
        {
            System.out.println(i + ":");
            ToEdit[i] = sc.next().charAt(i);
        }
        System.out.println(ToEdit);

    }

Thank you

1
  • char[] ToEdit = new char []; doesn't compile, hence you can't run your code , and you won't get an exception. Once you do pass a length in the new char[1234], then you can change the upper bound of the loop to reflect the length of the array: for (int i=0; i<ToEdit.length; i++) Commented Apr 30, 2018 at 5:20

2 Answers 2

2

The problem lies here: char[] ToEdit = new char [];.

On that line, you are creating an empty array without a size. You would need to change it to : char[] ToEdit = new char [5];.

Further more, you will need to change this: ToEdit[i] = sc.next().charAt(i); to this: ToEdit[i] = sc.next().charAt(0);. The problem with your current line is that even if you enter 1 character, your code will look for more.

As a side note, it would be recommended that you extract the number 5 as a variable. This will allow you to increase or decrease the amount of characters your program can process by changing just one location.

As a further excercise, you can take a look at lists and see how you can make your program more flexible, without having to define a size for the array.

Sign up to request clarification or add additional context in comments.

2 Comments

I tried that. Before I couldn't enter any value. with that, it would only let me input one and then fail.
Thank you for the recommendation tho, i'll look into lists
0

This wont compile as you need to add char array length first: char[] ToEdit = new char[5]; Then this code ToEdit[i] = sc.next().charAt(i); produces String array out of bound exception. Because charAt(i) each time find char at 0,1,2,3,4 and so on position in string as shown below (the output of your program). So you need to change this to ToEdit[i] = sc.next().charAt(0);

0: abcde 1: acx 2: acv 3: acvff 4: acdcdvc acvfd

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.