Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Page 1 of 2 12 LastLast
Results 1 to 25 of 29

Thread: [SOLVED] How to output a range of values from arraylist and user input

  1. #1
    Junior Member
    Join Date
    Sep 2022
    Posts
    22
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Question [SOLVED] How to output a range of values from arraylist and user input

    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 ;/
    Last edited by belinyom; September 11th, 2022 at 04:24 AM.

  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    24,911
    Thanks
    58
    Thanked 2,693 Times in 2,643 Posts

    Default Re: How to output a range of values from arraylist and user input

    Exception in thread "main" java.lang.IndexOutOfBoundsException: fromIndex = -1
    What line did that error happen on? How did the value of -1 come to be used as an index?
    The message says an invalid index of -1 was used on that line. The valid indexes range from 0 to the length -1.

    Note: You are mixing up the value of an index with the contents of the list at that index.
    For example, an index of 1 finds a value of 20 in the list.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Sep 2022
    Posts
    22
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: How to output a range of values from arraylist and user input

    I assume -1 was counted as the last index when I stopped the loop from running. How can I exclude -1 from inputNumber (input user in this case) and stop the while loop at the same time?

    Exception in thread "main" java.lang.IndexOutOfBoundsException: fromIndex = -1
    at java.base/java.util.AbstractList.subListRangeCheck(AbstractL ist.java:505)
    at java.base/java.util.ArrayList.subList(ArrayList.java:1138)
    at OnlyTheseNumbers.main(OnlyTheseNumbers.java:27)

    this is the error message I was refering to, do you mean it is located in line code 27?

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    24,911
    Thanks
    58
    Thanked 2,693 Times in 2,643 Posts

    Default Re: How to output a range of values from arraylist and user input

    at java.base/java.util.ArrayList.subList(ArrayList.java:1138)
    at OnlyTheseNumbers.main(OnlyTheseNumbers.java:27)
    That says the error was at line 27 where the code calls the subList method.

    You can see the contents of the list by printing it after the end of the loop that gets its contents.

    Look at the API doc for the indexOf method to see what values it returns. Is -1 ever returned?
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Sep 2022
    Posts
    22
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: How to output a range of values from arraylist and user input

    Quote Originally Posted by Norm View Post
    That says the error was at line 27 where the code calls the subList method.

    You can see the contents of the list by printing it after the end of the loop that gets its contents.

    Look at the API doc for the indexOf method to see what values it returns. Is -1 ever returned?
    Thank you for clarifying that part, I did print out the content of that array list by simply adding system.out.println(listOfNumbers) which shows me the whole set of an array list, if i input 5 random numbers, it outputs [1,2,3,4,5]

    what do I do in this case to only show a range of that array let's say from 1 to 3 or from 1 to 4? Do I remove the sublist and use another method?

    And to answer your question, I do not think an index of -1 will ever be returned because indices start from 0 to infinity, not from -1

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    24,911
    Thanks
    58
    Thanked 2,693 Times in 2,643 Posts

    Default Re: How to output a range of values from arraylist and user input

    I do not think an index of -1 will ever be returned
    Read the API doc for the indexOf method. It clearly says that a -1 can be returned.

    Add some print statements that print out the values of all the variables the code uses so that you can see what the computer sees when the code is executed.

    Note: You are mixing up the value of an index with the contents of the list at that index.
    For example, an index of 1 finds a value of 20 in the list.
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Junior Member
    Join Date
    Sep 2022
    Posts
    22
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: How to output a range of values from arraylist and user input

    Quote Originally Posted by Norm View Post
    Read the API doc for the indexOf method. It clearly says that a -1 can be returned.

    Add some print statements that print out the values of all the variables the code uses so that you can see what the computer sees when the code is executed.

    Note: You are mixing up the value of an index with the contents of the list at that index.
    For example, an index of 1 finds a value of 20 in the list.
    this turned out to be more confusing than I thought

    Why can it return -1 and what is the point of that?

    To clear my confusions,

    .size gives the size of an array by totalling the amount of indices (not their content, it only counts how many indices are there)

    .get retrieves the index number (not its content)

    .indexOf what does it do? it says that: "Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. More formally, returns the lowest index i such that Objects.equals(o, get(i)), or -1 if there is no such index."

    the definition of .indexOf is really confusing in netbeans and I really cannot get my head around it ;/

    .subList is defined by 2 parameters 1 is inclusive and the other one is exclusive, what does that even mean too?

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    24,911
    Thanks
    58
    Thanked 2,693 Times in 2,643 Posts

    Default Re: How to output a range of values from arraylist and user input

    Why can it return -1 and what is the point of that?
    It returns -1 if this list does not contain the element.
    How else can it say the value was not found?

    inclusive and the other one is exclusive, what does that even mean
    inclusive means it includes that value
    exclusive means it does not include that value
    Given a list: ABCDE
    ask for items including the first (index 0) through and excluding index 3 (D is @ index 3) would give ABC

    the definition of .indexOf is really confusing in netbeans
    Use the JAVA SE API doc: https://docs.oracle.com/javase/8/docs/api/index.html
    Find the class in the left hand frame, click it and then read all about its methods
    If you don't understand my answer, don't ignore it, ask a question.

  9. #9
    Junior Member
    Join Date
    Sep 2022
    Posts
    22
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: How to output a range of values from arraylist and user input

    Quote Originally Posted by Norm View Post
    inclusive means it includes that value
    exclusive means it does not include that value
    Given a list: ABCDE

    ask for items including the first (index 0) through and excluding index 3 (D is @ index 3) would give ABC
    Thank you for clarifying the concept, I have managed to pull the output as I wanted it to be. But, when I input any random numbers in an array list and try to input -1 to stop the loop, the while loop does not stop at all. Do you recommend me to ask a new question about that or do I continue in this topic? Because my problem is solved but not with the while loop break

    Kindly, take a look at my modified code
     
     
    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<>();
     
     
            while (true) 
            {
                int inputNumber1 = Integer.valueOf(inputReader.nextLine());
                if (inputNumber1 == -1) 
                {
                    break;
                } 
                listOfNumbers.add(inputNumber1);
            }
     
            int inputNumber2 = Integer.valueOf(inputReader.nextInt());
            System.out.println("From where? " + inputNumber2);
     
            int inputNumber3 = Integer.valueOf(inputReader.nextInt());
            System.out.println("To where? " + inputNumber3);
     
            System.out.println(listOfNumbers.subList(inputNumber2, inputNumber3 + 1));
     
        }
    }

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    24,911
    Thanks
    58
    Thanked 2,693 Times in 2,643 Posts

    Default Re: How to output a range of values from arraylist and user input

    input -1 to stop the loop, the while loop does not stop
    It does for me. Can you run the program, copy the output window and paste it here so I can see?
    If you don't understand my answer, don't ignore it, ask a question.

  11. #11
    Junior Member
    Join Date
    Sep 2022
    Posts
    22
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: How to output a range of values from arraylist and user input

    Quote Originally Posted by Norm View Post
    It does for me. Can you run the program, copy the output window and paste it here so I can see?
    10
    20
    30
    40
    50
    -1
    0
    From where? 0
    2
    To where? 2
    [10, 20, 30]

    After i inputted -1 the console output was still running. After I have inputted 0 and then 2, it gave me the range of element values inside an array list and then the loop stopped

    https://images2.imgbox.com/2b/ca/bZJq8q3N_o.png

    Is there a possibility to make the loop stop after I input -1 and can input 2 values for the range?

  12. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    24,911
    Thanks
    58
    Thanked 2,693 Times in 2,643 Posts

    Default Re: How to output a range of values from arraylist and user input

    The code reads the 0 before it prints out the From where message.
    The code to read the 0 is outside of the loop. Add a print statement after the loop that prints out the contents of the array.
    That will show you that the loop has exited.
    If you don't understand my answer, don't ignore it, ask a question.

  13. #13
    Junior Member
    Join Date
    Sep 2022
    Posts
    22
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: How to output a range of values from arraylist and user input

    Quote Originally Posted by Norm View Post
    The code reads the 0 before it prints out the From where message.
    The code to read the 0 is outside of the loop. Add a print statement after the loop that prints out the contents of the array.
    That will show you that the loop has exited.
    that is really strange: https://imgbox.com/9Wi67jLg

    I have added system.out.println(listOfNumbers) to show the set or collection of array, the loop still did not break. why is the IF condition not working?

  14. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    24,911
    Thanks
    58
    Thanked 2,693 Times in 2,643 Posts

    Default Re: How to output a range of values from arraylist and user input

    Please copy the console's contents and paste it here. No images. Text can not be copied from an image to include in a response.

    the loop still did not break. why is the IF condition not working?
    Please post the new code and the contents of the console from when the program executes.
    If you don't understand my answer, don't ignore it, ask a question.

  15. #15
    Junior Member
    Join Date
    Sep 2022
    Posts
    22
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: How to output a range of values from arraylist and user input

    Quote Originally Posted by Norm View Post
    Please copy the console's contents and paste it here. No images. Text can not be copied from an image to include in a response.


    Please post the new code and the contents of the console from when the program executes.

     
    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<>();
     
     
            while (true) 
            {
                int inputNumber1 = Integer.valueOf(inputReader.nextLine());
                if (inputNumber1 == -1) 
                {
                    break;
                } 
                listOfNumbers.add(inputNumber1);
            }
     
            System.out.println(listOfNumbers);
     
            int inputNumber2 = Integer.valueOf(inputReader.nextInt());
            System.out.println("From where? " + inputNumber2);
     
            int inputNumber3 = Integer.valueOf(inputReader.nextInt());
            System.out.println("To where? " + inputNumber3);
     
            System.out.println(listOfNumbers.subList(inputNumber2, inputNumber3 + 1));
     
        }
    }


    Console output
    10
    20
    30
    40
    50
    60
    70
    -1
    [10, 20, 30, 40, 50, 60, 70]
    0
    From where? 0
    3
    To where? 3
    [10, 20, 30, 40]

  16. #16
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    24,911
    Thanks
    58
    Thanked 2,693 Times in 2,643 Posts

    Default Re: How to output a range of values from arraylist and user input

    the loop still did not break. why is the IF condition not working?
    I don't see where the problem is. The console output looks as expected.

    What do you think the output should look like? Can you post what you expect to see?
    If you don't understand my answer, don't ignore it, ask a question.

  17. #17
    Junior Member
    Join Date
    Sep 2022
    Posts
    22
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: How to output a range of values from arraylist and user input

    Quote Originally Posted by Norm View Post
    I don't see where the problem is. The console output looks as expected.

    What do you think the output should look like? Can you post what you expect to see?
    the output should look exactly like this according to the exercise:
    10
    20
    30
    40
    50
    -1
    From where? 0
    To where? 2
    [10, 20, 30]


    as opposed to my current output
    10
    20
    30
    40
    50
    60
    70
    -1
    [10, 20, 30, 40, 50, 60, 70]
    0
    From where? 0
    3
    To where? 3
    [10, 20, 30, 40]

    perhaps the problem is with re-initiating the inputNumber integer to the scanner 2 times (so the scanner can read again with a whole new scanning) but this is just an assumption

  18. #18
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    24,911
    Thanks
    58
    Thanked 2,693 Times in 2,643 Posts

    Default Re: How to output a range of values from arraylist and user input

    When you type in the input 0 and 3, they are displayed on the console where and when they are typed.
    To have them appear after the messages: From where? and To where?
    you need to print the message to the console first without a line-end
    and then read the user's input after the message was printed.
    If you don't understand my answer, don't ignore it, ask a question.

  19. #19
    Junior Member
    Join Date
    Sep 2022
    Posts
    22
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: How to output a range of values from arraylist and user input

    I do not think that this is possible because I still need to declare a new scanner input variable for 2 values and the declaration has to be done before printing it out. How can I print something that has not been declared before?

    I have tried declaring both inputNumber2 and 3 before and outside the loop, inside the loop and after outside the loop, there was no result.

  20. #20
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    24,911
    Thanks
    58
    Thanked 2,693 Times in 2,643 Posts

    Default Re: How to output a range of values from arraylist and user input

    I do not think that this is possible
    Did you try it?
    The code would like like this:
    print the message
    read user's response to the message

    If you print the value that was read, it will appear on the console 2 times ( that is the current problem)
    first time would be when entered
    second time when printed
    If you don't understand my answer, don't ignore it, ask a question.

  21. #21
    Junior Member
    Join Date
    Sep 2022
    Posts
    22
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: How to output a range of values from arraylist and user input

    Quote Originally Posted by Norm View Post
    Did you try it?
    The code would like like this:
    print the message
    read user's response to the message

    If you print the value that was read, it will appear on the console 2 times ( that is the current problem)
    first time would be when entered
    second time when printed
    I have tried it numerous times. If a question is asked to the user, the user is able to respond to that question. But in Java, a variable must be declared before a question is asked. If there is a way to oppose what I have just said, then please prove it in coding because I really cannot think much about it and I will just leave it for now. I have spent the entire day trying to solve this entire exercise and time is against me.

  22. #22
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    24,911
    Thanks
    58
    Thanked 2,693 Times in 2,643 Posts

    Default Re: How to output a range of values from arraylist and user input

    a variable must be declared before a question is asked
    That is not true. A program can ask many questions without declaring any variables.
    A variable must be declared before it is used.
    Asking a question and using a variable do not need to be related.

    The code would like like this:
    print the message <<< NO NEED for any variables here. Can be all text
    read user's response to the message <<< This will need a variable to hold user's input
    If you don't understand my answer, don't ignore it, ask a question.

  23. #23
    Junior Member
    Join Date
    Sep 2022
    Posts
    22
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: How to output a range of values from arraylist and user input

    Quote Originally Posted by Norm View Post
    That is not true. A program can ask many questions without declaring any variables.
    A variable must be declared before it is used.
    Asking a question and using a variable do not need to be related.
    Quite interesting, even though I struggled with a simple exercise, I did learn a lot.

    I thank you for your insight and understanding.

    I have finally solved the problem, would you like me to provide the solution as a reference to others or just keep it as it is from here?

  24. #24
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    24,911
    Thanks
    58
    Thanked 2,693 Times in 2,643 Posts

    Default Re: How to output a range of values from arraylist and user input

    Glad you got it working.

    A working solution might be helpful for others.
    If you don't understand my answer, don't ignore it, ask a question.

  25. #25
    Junior Member
    Join Date
    Sep 2022
    Posts
    22
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: How to output a range of values from arraylist and user input

    Quote Originally Posted by Norm View Post
    Glad you got it working.

    A working solution might be helpful for others.
    Thank you once again

     
    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 inputNumber1;
            int startIndex;
            int endIndex;
     
            while (true) {
                inputNumber1 = Integer.valueOf(inputReader.nextLine());
                if (inputNumber1 == -1) {
                    break;
                }
                listOfNumbers.add(inputNumber1);
            }
     
            System.out.println("From where? ");
            startIndex = Integer.valueOf(inputReader.nextInt());
     
            System.out.println("To where? ");
            endIndex = Integer.valueOf(inputReader.nextInt());
     
            System.out.println(listOfNumbers.subList(startIndex, endIndex + 1));
        }
    }

Page 1 of 2 12 LastLast

Similar Threads

  1. Replies: 1
    Last Post: May 16th, 2012, 05:15 PM
  2. user input going to wrong ArrayList
    By havinFun in forum What's Wrong With My Code?
    Replies: 1
    Last Post: April 15th, 2012, 02:58 PM
  3. [SOLVED] Returning ArrayList via user input
    By IanSawyer in forum Collections and Generics
    Replies: 4
    Last Post: March 27th, 2012, 05:40 PM
  4. Need help with user input/output for GUI.
    By Tctwins in forum AWT / Java Swing
    Replies: 6
    Last Post: February 20th, 2012, 04:13 PM
  5. JTable Updating String Values from User Input
    By aussiemcgr in forum AWT / Java Swing
    Replies: 5
    Last Post: August 3rd, 2010, 01:48 PM

Tags for this Thread