Hello there, I have been stuck with this exercise for quite some time and I really do not know how to meet its requirements.
I am trying to input random numbers [10, 20, 30, 40 and 50] to an array list, after I input -1 the while loop will stop running and the array list will stop collecting numbers.
After that, I want the user to input a first and an end value (index) assuming that the user knows how many numbers there are in an array list, to retrieve a range of values and after the loop is broken. Let's say the user inputs 10 and 30, the output should be [10, 20 and 30]
there are 2 error messages saying:
Something unexpected happened. The public static void main(String[] args) method of 'class OnlyTheseNumbers' class has disappeared
or something unexpected happened. More info: java.lang.IndexOutOfBoundsException: fromIndex = -1
Exception in thread "main" java.lang.IndexOutOfBoundsException: fromIndex = -1
import java.util.ArrayList; import java.util.Scanner; public class OnlyTheseNumbers { public static void main(String[] args) { Scanner inputReader = new Scanner(System.in); ArrayList<Integer> listOfNumbers = new ArrayList<>(); int inputNumber; while (true) { inputNumber = Integer.valueOf(inputReader.nextLine()); if (inputNumber == -1) { break; } else { listOfNumbers.add(inputNumber); } } inputNumber = Integer.valueOf(inputReader.nextLine()); System.out.println("From where? " + listOfNumbers.get(inputNumber)); int startIndex = listOfNumbers.indexOf(inputNumber); inputNumber = Integer.valueOf(inputReader.nextLine()); System.out.println("To where? " + listOfNumbers.get(inputNumber)); int endIndex = listOfNumbers.indexOf(inputNumber); System.out.println(listOfNumbers.subList(startIndex, endIndex + 1)); } }
Sample output according to the exercise should be like the following
10 20 30 40 50 ^random numbers to input^ -1 input -1 to stop the loop but does it stop array collection of numbers? From where? 0 To where? 2 ^numbers are inputted based on indices^ 10 20 30 ^output^
Can someone help please? I am still new to Java Programming and many assignments have been given to me in a short period of time ;/