I want to select a random string from my ArrayList and then print that string. here is my code:
public class Operator {
Random rand = new Random();
ArrayList<String> myArray = new ArrayList<String>();
public void CreateArrayList() {
myArray.add("add");
myArray.add("subtract");
myArray.add("multiply");
myArray.add("divide");
myArray.add("remainder");
myArray.add("greaterthan");
myArray.add("lessthan");
myArray.add("max");
myArray.add("min");
myArray.add("power");
try {
FileReader inFile = new FileReader("data/numbers2.txt");
Scanner scanner = new Scanner(inFile);
String line = scanner.nextLine();
System.out.println(line);
scanner.close();
}
catch (Exception ex) {
ex.printStackTrace();}
}
{
}
public void showOperations() {
int x = (int) Math.floor(Math.random()*10);
int y = (int) Math.floor(Math.random()*10);
int z = rand.nextInt(10);
System.out.println(x+" "+ myArray.get( z )+" "+ y );
}
}
The output should be for example "3 add 4". However, ever time I run the code, I get
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 4, Size: 0 at java.util.ArrayList.rangeCheck(Unknown Source) at java.util.ArrayList.get(Unknown Source) at hw2p2.Operator.showOperations(Operator.java:42) at hw2p2.Launcher.main(Launcher.java:9)
CreateArrayList()....int z = rand.nextInt(10);should beint z = rand.nextInt(myArray.size());