Finding a substring within an array list made from file, java











up vote
1
down vote

favorite












I have a text file from which I've created an Array list. Each line = one element of collection. Is there any way to find a specific word in that line, and if it's found, output that line to console?
Right now that part of my code looks somewhat like this:



protected static void FindBook() {
System.out.print("Author's name: ");
String neededauthor = sc.nextLine();
for (int k=0; k<=books.size(); k++) {
if (books.get(k).contains(neededauthor))
System.out.println(books.get(k));
}
}


But it's giving me



Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0


Update: I've tried to fix it, and now the exception is gone, but it doesn't work either. After I enter the name, the method stops working and just doesn't do anything, where it should output that line. I don't understand what the matter is










share|improve this question




















  • 3




    k<=books.size() -> k<books.size()
    – Eran
    Nov 11 at 13:27















up vote
1
down vote

favorite












I have a text file from which I've created an Array list. Each line = one element of collection. Is there any way to find a specific word in that line, and if it's found, output that line to console?
Right now that part of my code looks somewhat like this:



protected static void FindBook() {
System.out.print("Author's name: ");
String neededauthor = sc.nextLine();
for (int k=0; k<=books.size(); k++) {
if (books.get(k).contains(neededauthor))
System.out.println(books.get(k));
}
}


But it's giving me



Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0


Update: I've tried to fix it, and now the exception is gone, but it doesn't work either. After I enter the name, the method stops working and just doesn't do anything, where it should output that line. I don't understand what the matter is










share|improve this question




















  • 3




    k<=books.size() -> k<books.size()
    – Eran
    Nov 11 at 13:27













up vote
1
down vote

favorite









up vote
1
down vote

favorite











I have a text file from which I've created an Array list. Each line = one element of collection. Is there any way to find a specific word in that line, and if it's found, output that line to console?
Right now that part of my code looks somewhat like this:



protected static void FindBook() {
System.out.print("Author's name: ");
String neededauthor = sc.nextLine();
for (int k=0; k<=books.size(); k++) {
if (books.get(k).contains(neededauthor))
System.out.println(books.get(k));
}
}


But it's giving me



Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0


Update: I've tried to fix it, and now the exception is gone, but it doesn't work either. After I enter the name, the method stops working and just doesn't do anything, where it should output that line. I don't understand what the matter is










share|improve this question















I have a text file from which I've created an Array list. Each line = one element of collection. Is there any way to find a specific word in that line, and if it's found, output that line to console?
Right now that part of my code looks somewhat like this:



protected static void FindBook() {
System.out.print("Author's name: ");
String neededauthor = sc.nextLine();
for (int k=0; k<=books.size(); k++) {
if (books.get(k).contains(neededauthor))
System.out.println(books.get(k));
}
}


But it's giving me



Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0


Update: I've tried to fix it, and now the exception is gone, but it doesn't work either. After I enter the name, the method stops working and just doesn't do anything, where it should output that line. I don't understand what the matter is







java arraylist collections substring






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 11 at 13:52

























asked Nov 11 at 13:26









Nene

43




43








  • 3




    k<=books.size() -> k<books.size()
    – Eran
    Nov 11 at 13:27














  • 3




    k<=books.size() -> k<books.size()
    – Eran
    Nov 11 at 13:27








3




3




k<=books.size() -> k<books.size()
– Eran
Nov 11 at 13:27




k<=books.size() -> k<books.size()
– Eran
Nov 11 at 13:27












3 Answers
3






active

oldest

votes

















up vote
1
down vote













As the other anwers already say, there is a problem when accessing an index that is not there:



books.get(books.size())


The index runs from 0 to size()-1, so size() is out of bounds.



You can avoid the index completely and make your code simpler by using a foreach loop like this:



for (Book book: books)
if (book.contains(neededauthor))
System.out.println(book);


I assumed that the type of books is some collection of type Book.






share|improve this answer




























    up vote
    0
    down vote













    I think your code looks correct, but there is one problem.




    for (int k=0; k<=books.size(); k++) {




    If k starts at 0, it cannot be equal to books.size(), because that would mean that it will go through the for loop one more time than there are elements in books.size().



    Try changing it to for (int k = 0; k < books.size(); k++) {



    Besides that, if your ArrayList books has values in it, your code should work.






    share|improve this answer




























      up vote
      0
      down vote













      Use this part k<books.size() instead of k<=books.size() it should be only less than. Not less than and equal. Also change your method name to findBook() since its not following Java camel notation






      share|improve this answer





















        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53249188%2ffinding-a-substring-within-an-array-list-made-from-file-java%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes








        up vote
        1
        down vote













        As the other anwers already say, there is a problem when accessing an index that is not there:



        books.get(books.size())


        The index runs from 0 to size()-1, so size() is out of bounds.



        You can avoid the index completely and make your code simpler by using a foreach loop like this:



        for (Book book: books)
        if (book.contains(neededauthor))
        System.out.println(book);


        I assumed that the type of books is some collection of type Book.






        share|improve this answer

























          up vote
          1
          down vote













          As the other anwers already say, there is a problem when accessing an index that is not there:



          books.get(books.size())


          The index runs from 0 to size()-1, so size() is out of bounds.



          You can avoid the index completely and make your code simpler by using a foreach loop like this:



          for (Book book: books)
          if (book.contains(neededauthor))
          System.out.println(book);


          I assumed that the type of books is some collection of type Book.






          share|improve this answer























            up vote
            1
            down vote










            up vote
            1
            down vote









            As the other anwers already say, there is a problem when accessing an index that is not there:



            books.get(books.size())


            The index runs from 0 to size()-1, so size() is out of bounds.



            You can avoid the index completely and make your code simpler by using a foreach loop like this:



            for (Book book: books)
            if (book.contains(neededauthor))
            System.out.println(book);


            I assumed that the type of books is some collection of type Book.






            share|improve this answer












            As the other anwers already say, there is a problem when accessing an index that is not there:



            books.get(books.size())


            The index runs from 0 to size()-1, so size() is out of bounds.



            You can avoid the index completely and make your code simpler by using a foreach loop like this:



            for (Book book: books)
            if (book.contains(neededauthor))
            System.out.println(book);


            I assumed that the type of books is some collection of type Book.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 11 at 13:42









            Donat

            54626




            54626
























                up vote
                0
                down vote













                I think your code looks correct, but there is one problem.




                for (int k=0; k<=books.size(); k++) {




                If k starts at 0, it cannot be equal to books.size(), because that would mean that it will go through the for loop one more time than there are elements in books.size().



                Try changing it to for (int k = 0; k < books.size(); k++) {



                Besides that, if your ArrayList books has values in it, your code should work.






                share|improve this answer

























                  up vote
                  0
                  down vote













                  I think your code looks correct, but there is one problem.




                  for (int k=0; k<=books.size(); k++) {




                  If k starts at 0, it cannot be equal to books.size(), because that would mean that it will go through the for loop one more time than there are elements in books.size().



                  Try changing it to for (int k = 0; k < books.size(); k++) {



                  Besides that, if your ArrayList books has values in it, your code should work.






                  share|improve this answer























                    up vote
                    0
                    down vote










                    up vote
                    0
                    down vote









                    I think your code looks correct, but there is one problem.




                    for (int k=0; k<=books.size(); k++) {




                    If k starts at 0, it cannot be equal to books.size(), because that would mean that it will go through the for loop one more time than there are elements in books.size().



                    Try changing it to for (int k = 0; k < books.size(); k++) {



                    Besides that, if your ArrayList books has values in it, your code should work.






                    share|improve this answer












                    I think your code looks correct, but there is one problem.




                    for (int k=0; k<=books.size(); k++) {




                    If k starts at 0, it cannot be equal to books.size(), because that would mean that it will go through the for loop one more time than there are elements in books.size().



                    Try changing it to for (int k = 0; k < books.size(); k++) {



                    Besides that, if your ArrayList books has values in it, your code should work.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 11 at 13:32









                    Ishaan

                    7011417




                    7011417






















                        up vote
                        0
                        down vote













                        Use this part k<books.size() instead of k<=books.size() it should be only less than. Not less than and equal. Also change your method name to findBook() since its not following Java camel notation






                        share|improve this answer

























                          up vote
                          0
                          down vote













                          Use this part k<books.size() instead of k<=books.size() it should be only less than. Not less than and equal. Also change your method name to findBook() since its not following Java camel notation






                          share|improve this answer























                            up vote
                            0
                            down vote










                            up vote
                            0
                            down vote









                            Use this part k<books.size() instead of k<=books.size() it should be only less than. Not less than and equal. Also change your method name to findBook() since its not following Java camel notation






                            share|improve this answer












                            Use this part k<books.size() instead of k<=books.size() it should be only less than. Not less than and equal. Also change your method name to findBook() since its not following Java camel notation







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 11 at 13:34









                            Sand

                            7259




                            7259






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.





                                Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                Please pay close attention to the following guidance:


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53249188%2ffinding-a-substring-within-an-array-list-made-from-file-java%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                Full-time equivalent

                                さくらももこ

                                13 indicted, 8 arrested in Calif. drug cartel investigation