java.lang.IndexOutOfBoundsException: Index: 3, Tab count: 3 [duplicate]
This is my code. It is a random string generator. When I run it, if the number of letters and characters added together are less than the desired amount of digits, I get an error code as shown below. Can someone help me on fixing this?
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class list {
public static void main(String[] args) {
// TODO Auto-generated method stub
Random num = new Random();
System.out.println("How many characters do you want?");
Scanner Digits = new Scanner(System.in);
int digits = Integer.parseInt(Digits.nextLine());
System.out.println("How many different numbers do you want? 1-10 please");
int number = Integer.parseInt(Digits.nextLine());
System.out.println("Which letters do you want? One at a time, press enter after each letter. If done, just press enter.");
List<String> characters = new ArrayList<String>();
while (true) {
System.out.println("Add your characters.");
String character = Digits.nextLine();
if (character.equals("")) {
break;
} else {
characters.add(character);
}
}
List<Object> andrew = new ArrayList<Object>();
for (int x = 0; x < digits; x++) {
andrew.add(num.nextInt(number));
andrew.add(characters.get(x));
}
for (int x = 0; x < andrew.size(); x += 2) {
System.out.print(andrew.get(x));
}
}
}
Exception:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 3, Size: 3
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at list.main(list.java:33)
Solution 1:
An IndexOutOfBoundsException
occurs when you try to select a value from an array that goes beyond its size. In this example, you're trying to get the value at [3]. You can read this much off the stack trace:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 3, Size: 3
Arrays in java begin at index [0]
, not index [1]
, and so an array of length 3 will only have indices [0]
, [1]
and [2]
.
Trying to get the value at [3]
when the array only extends to [2]
will cause this error.
HOWEVER, the other answer is actually wrong about where the problem is. The stack trace says it's at line 33 which is this:
andrew.add(characters.get(x));