Using Scanner to analyse a string, letter by letter, in a for loop (Throwing IndexOutOfBoundExceptions)












1














I need to count the frequency at which a letter appears in a string.



To do this, I thought about using a scanner object, passing the string to it




Scanner s = new Scanner(String)




and using the next() method to analyse each char with a switch statement.



I've done a search on these boards and have devised the following :-



for (int i = 0; i < outputString.length(); i++) {
Scanner s = new Scanner(outputString);
char letter = s.next().charAt(i);
switch (letter) {
switch code;
}


This appears to work when the string I'm analysing contains anything (-_z1 etc..) other than whitespaces which will cause the program to throw a String.IndexOutOfBoundException (4).



Is there something else I can try or should I just remove all the whitespaces from the word (i.e. I'm thinking by creating a newword string using a for loop to add each string.charAt(i) != ' ').



Edit: I forgot that the scanner was in the for loop, I'll take it out. Secondly, not sure if it changes matters but I'm trying to count the no of times each letter in the alphabet in the string appears, not just one type of letter. Thanks for your comments!



Thanks in advance,

Kevin










share|improve this question
























  • This code doesn't make much sense. If the goal is to go through each letter of outputString, why are you creating a Scanner and calling next(), instead of just getting the character at index i of outputString directly?
    – JB Nizet
    Nov 11 at 15:31










  • I understand what you are trying to achieve but this is a complicated way. Why not get the String in a String object and then manually check directly?
    – Taslim
    Nov 11 at 15:32










  • @JBNizet - I'm not sure, it must have skipped my mind. I've now changed it to outputString.charAt(i) which is much more cleaner - no need to remove any spaces!
    – kevin0110w
    Nov 13 at 11:06
















1














I need to count the frequency at which a letter appears in a string.



To do this, I thought about using a scanner object, passing the string to it




Scanner s = new Scanner(String)




and using the next() method to analyse each char with a switch statement.



I've done a search on these boards and have devised the following :-



for (int i = 0; i < outputString.length(); i++) {
Scanner s = new Scanner(outputString);
char letter = s.next().charAt(i);
switch (letter) {
switch code;
}


This appears to work when the string I'm analysing contains anything (-_z1 etc..) other than whitespaces which will cause the program to throw a String.IndexOutOfBoundException (4).



Is there something else I can try or should I just remove all the whitespaces from the word (i.e. I'm thinking by creating a newword string using a for loop to add each string.charAt(i) != ' ').



Edit: I forgot that the scanner was in the for loop, I'll take it out. Secondly, not sure if it changes matters but I'm trying to count the no of times each letter in the alphabet in the string appears, not just one type of letter. Thanks for your comments!



Thanks in advance,

Kevin










share|improve this question
























  • This code doesn't make much sense. If the goal is to go through each letter of outputString, why are you creating a Scanner and calling next(), instead of just getting the character at index i of outputString directly?
    – JB Nizet
    Nov 11 at 15:31










  • I understand what you are trying to achieve but this is a complicated way. Why not get the String in a String object and then manually check directly?
    – Taslim
    Nov 11 at 15:32










  • @JBNizet - I'm not sure, it must have skipped my mind. I've now changed it to outputString.charAt(i) which is much more cleaner - no need to remove any spaces!
    – kevin0110w
    Nov 13 at 11:06














1












1








1







I need to count the frequency at which a letter appears in a string.



To do this, I thought about using a scanner object, passing the string to it




Scanner s = new Scanner(String)




and using the next() method to analyse each char with a switch statement.



I've done a search on these boards and have devised the following :-



for (int i = 0; i < outputString.length(); i++) {
Scanner s = new Scanner(outputString);
char letter = s.next().charAt(i);
switch (letter) {
switch code;
}


This appears to work when the string I'm analysing contains anything (-_z1 etc..) other than whitespaces which will cause the program to throw a String.IndexOutOfBoundException (4).



Is there something else I can try or should I just remove all the whitespaces from the word (i.e. I'm thinking by creating a newword string using a for loop to add each string.charAt(i) != ' ').



Edit: I forgot that the scanner was in the for loop, I'll take it out. Secondly, not sure if it changes matters but I'm trying to count the no of times each letter in the alphabet in the string appears, not just one type of letter. Thanks for your comments!



Thanks in advance,

Kevin










share|improve this question















I need to count the frequency at which a letter appears in a string.



To do this, I thought about using a scanner object, passing the string to it




Scanner s = new Scanner(String)




and using the next() method to analyse each char with a switch statement.



I've done a search on these boards and have devised the following :-



for (int i = 0; i < outputString.length(); i++) {
Scanner s = new Scanner(outputString);
char letter = s.next().charAt(i);
switch (letter) {
switch code;
}


This appears to work when the string I'm analysing contains anything (-_z1 etc..) other than whitespaces which will cause the program to throw a String.IndexOutOfBoundException (4).



Is there something else I can try or should I just remove all the whitespaces from the word (i.e. I'm thinking by creating a newword string using a for loop to add each string.charAt(i) != ' ').



Edit: I forgot that the scanner was in the for loop, I'll take it out. Secondly, not sure if it changes matters but I'm trying to count the no of times each letter in the alphabet in the string appears, not just one type of letter. Thanks for your comments!



Thanks in advance,

Kevin







java java.util.scanner






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 11 at 17:24

























asked Nov 11 at 15:26









kevin0110w

62




62












  • This code doesn't make much sense. If the goal is to go through each letter of outputString, why are you creating a Scanner and calling next(), instead of just getting the character at index i of outputString directly?
    – JB Nizet
    Nov 11 at 15:31










  • I understand what you are trying to achieve but this is a complicated way. Why not get the String in a String object and then manually check directly?
    – Taslim
    Nov 11 at 15:32










  • @JBNizet - I'm not sure, it must have skipped my mind. I've now changed it to outputString.charAt(i) which is much more cleaner - no need to remove any spaces!
    – kevin0110w
    Nov 13 at 11:06


















  • This code doesn't make much sense. If the goal is to go through each letter of outputString, why are you creating a Scanner and calling next(), instead of just getting the character at index i of outputString directly?
    – JB Nizet
    Nov 11 at 15:31










  • I understand what you are trying to achieve but this is a complicated way. Why not get the String in a String object and then manually check directly?
    – Taslim
    Nov 11 at 15:32










  • @JBNizet - I'm not sure, it must have skipped my mind. I've now changed it to outputString.charAt(i) which is much more cleaner - no need to remove any spaces!
    – kevin0110w
    Nov 13 at 11:06
















This code doesn't make much sense. If the goal is to go through each letter of outputString, why are you creating a Scanner and calling next(), instead of just getting the character at index i of outputString directly?
– JB Nizet
Nov 11 at 15:31




This code doesn't make much sense. If the goal is to go through each letter of outputString, why are you creating a Scanner and calling next(), instead of just getting the character at index i of outputString directly?
– JB Nizet
Nov 11 at 15:31












I understand what you are trying to achieve but this is a complicated way. Why not get the String in a String object and then manually check directly?
– Taslim
Nov 11 at 15:32




I understand what you are trying to achieve but this is a complicated way. Why not get the String in a String object and then manually check directly?
– Taslim
Nov 11 at 15:32












@JBNizet - I'm not sure, it must have skipped my mind. I've now changed it to outputString.charAt(i) which is much more cleaner - no need to remove any spaces!
– kevin0110w
Nov 13 at 11:06




@JBNizet - I'm not sure, it must have skipped my mind. I've now changed it to outputString.charAt(i) which is much more cleaner - no need to remove any spaces!
– kevin0110w
Nov 13 at 11:06












5 Answers
5






active

oldest

votes


















0














Here is an alternative way to solve this problem provided on another question. (can't leave comments yet.. so have to put as an answer...)
How to count frequency of characters in a string?






share|improve this answer





























    0














    While having this:



    Scanner s = new Scanner(outputString);


    Inside the for loop, you're creating a new Scanner in every iteration (not efficient nor what you want).



    If you already have a String called outputString you can access its characters / letters directly as follows:



    for (int i = 0; i < outputString.length(); i++) {
    char letter = outputString.charAt(i);
    //The rest of you code here
    }





    share|improve this answer





























      0














      I strongly think you're complicating things by using that approach. You can simply pass the String (and the char you are searching for) into a method just like the one below:



      public int checkFreq(char letter, String word){
      int freq = 0;

      for(int i = 0; i < word.length(); i++){
      if((word.charAt(i)) == letter){
      freq++;
      }
      }

      return freq;
      }


      I hope this helps.. Merry coding!






      share|improve this answer































        0














        You should follow the above solution for getting repeated characters in a string. However, I will just give you a hint about why you are getting the exception



        consider the following code:






        String outputString = "Pre ";
        for (int i = 0; i < outputString.length(); i++) {
        Scanner s = new Scanner(outputString);
        System.out.println(outputString.length()); // output is 4
        System.out.println(s.next().length()); //output is 3, not considering the space
        //char letter = s.next().charAt(i);
        //System.out.println(letter);
        }








        share|improve this answer





























          0














          First of all, you shold not create new Scanner each time when you ready next character. Do it only once, before for loop.



          Second - to read scanner character by character, you have set delimeter as "". In this case, scan.next() returns next character.



          Third - you use Scanner to analyze string, that's OK (not optimal and overhead, but OK). Then do create new Scanner isntance and rely on it's data, but not on length of the goven string; do use Scanner.hasNext() method. I mean that all you need, is just add hasNext() to be sure that more characters exists in the scanner's stream:



          try (Scanner scan = new Scanner(outputString)) {
          scan.useDelimiter(""); // to make scan.next() return one single character

          while (scan.hasNext()) {
          char ch = scan.next().charAt(0); // next() returns String with one character
          // do your work
          }
          }


          P.S. This is code examples, how you can cound character frequencey in the given string with different ways. Probably, one of them you'll find more relevant to your task.



          // this is your approach
          public static int characterFrequency(String str, char ch) {
          try (Scanner scan = new Scanner(str)) {
          scan.useDelimiter("");
          int count = 0;

          while (scan.hasNext())
          count += scan.next().charAt(0) == ch ? 1 : 0;

          return count;
          }
          }

          // this one is the most efficient
          public static int characterFrequency(String str, char ch) {
          int count = 0;

          for (int i = 0; i < str.length(); i++)
          count += str.charAt(i) == ch ? 1 : 0;

          return count;
          }

          // this one is the smallest of code
          public static int characterFrequency(String str, char ch) {
          return (int)str.chars().filter(e -> e == ch).count();
          }





          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',
            autoActivateHeartbeat: false,
            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%2f53250205%2fusing-scanner-to-analyse-a-string-letter-by-letter-in-a-for-loop-throwing-ind%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            5 Answers
            5






            active

            oldest

            votes








            5 Answers
            5






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            Here is an alternative way to solve this problem provided on another question. (can't leave comments yet.. so have to put as an answer...)
            How to count frequency of characters in a string?






            share|improve this answer


























              0














              Here is an alternative way to solve this problem provided on another question. (can't leave comments yet.. so have to put as an answer...)
              How to count frequency of characters in a string?






              share|improve this answer
























                0












                0








                0






                Here is an alternative way to solve this problem provided on another question. (can't leave comments yet.. so have to put as an answer...)
                How to count frequency of characters in a string?






                share|improve this answer












                Here is an alternative way to solve this problem provided on another question. (can't leave comments yet.. so have to put as an answer...)
                How to count frequency of characters in a string?







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 11 at 15:37









                PMoe

                265




                265

























                    0














                    While having this:



                    Scanner s = new Scanner(outputString);


                    Inside the for loop, you're creating a new Scanner in every iteration (not efficient nor what you want).



                    If you already have a String called outputString you can access its characters / letters directly as follows:



                    for (int i = 0; i < outputString.length(); i++) {
                    char letter = outputString.charAt(i);
                    //The rest of you code here
                    }





                    share|improve this answer


























                      0














                      While having this:



                      Scanner s = new Scanner(outputString);


                      Inside the for loop, you're creating a new Scanner in every iteration (not efficient nor what you want).



                      If you already have a String called outputString you can access its characters / letters directly as follows:



                      for (int i = 0; i < outputString.length(); i++) {
                      char letter = outputString.charAt(i);
                      //The rest of you code here
                      }





                      share|improve this answer
























                        0












                        0








                        0






                        While having this:



                        Scanner s = new Scanner(outputString);


                        Inside the for loop, you're creating a new Scanner in every iteration (not efficient nor what you want).



                        If you already have a String called outputString you can access its characters / letters directly as follows:



                        for (int i = 0; i < outputString.length(); i++) {
                        char letter = outputString.charAt(i);
                        //The rest of you code here
                        }





                        share|improve this answer












                        While having this:



                        Scanner s = new Scanner(outputString);


                        Inside the for loop, you're creating a new Scanner in every iteration (not efficient nor what you want).



                        If you already have a String called outputString you can access its characters / letters directly as follows:



                        for (int i = 0; i < outputString.length(); i++) {
                        char letter = outputString.charAt(i);
                        //The rest of you code here
                        }






                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Nov 11 at 15:40









                        Frakcool

                        7,62052557




                        7,62052557























                            0














                            I strongly think you're complicating things by using that approach. You can simply pass the String (and the char you are searching for) into a method just like the one below:



                            public int checkFreq(char letter, String word){
                            int freq = 0;

                            for(int i = 0; i < word.length(); i++){
                            if((word.charAt(i)) == letter){
                            freq++;
                            }
                            }

                            return freq;
                            }


                            I hope this helps.. Merry coding!






                            share|improve this answer




























                              0














                              I strongly think you're complicating things by using that approach. You can simply pass the String (and the char you are searching for) into a method just like the one below:



                              public int checkFreq(char letter, String word){
                              int freq = 0;

                              for(int i = 0; i < word.length(); i++){
                              if((word.charAt(i)) == letter){
                              freq++;
                              }
                              }

                              return freq;
                              }


                              I hope this helps.. Merry coding!






                              share|improve this answer


























                                0












                                0








                                0






                                I strongly think you're complicating things by using that approach. You can simply pass the String (and the char you are searching for) into a method just like the one below:



                                public int checkFreq(char letter, String word){
                                int freq = 0;

                                for(int i = 0; i < word.length(); i++){
                                if((word.charAt(i)) == letter){
                                freq++;
                                }
                                }

                                return freq;
                                }


                                I hope this helps.. Merry coding!






                                share|improve this answer














                                I strongly think you're complicating things by using that approach. You can simply pass the String (and the char you are searching for) into a method just like the one below:



                                public int checkFreq(char letter, String word){
                                int freq = 0;

                                for(int i = 0; i < word.length(); i++){
                                if((word.charAt(i)) == letter){
                                freq++;
                                }
                                }

                                return freq;
                                }


                                I hope this helps.. Merry coding!







                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited Nov 11 at 15:44

























                                answered Nov 11 at 15:39









                                Taslim

                                1,19741525




                                1,19741525























                                    0














                                    You should follow the above solution for getting repeated characters in a string. However, I will just give you a hint about why you are getting the exception



                                    consider the following code:






                                    String outputString = "Pre ";
                                    for (int i = 0; i < outputString.length(); i++) {
                                    Scanner s = new Scanner(outputString);
                                    System.out.println(outputString.length()); // output is 4
                                    System.out.println(s.next().length()); //output is 3, not considering the space
                                    //char letter = s.next().charAt(i);
                                    //System.out.println(letter);
                                    }








                                    share|improve this answer


























                                      0














                                      You should follow the above solution for getting repeated characters in a string. However, I will just give you a hint about why you are getting the exception



                                      consider the following code:






                                      String outputString = "Pre ";
                                      for (int i = 0; i < outputString.length(); i++) {
                                      Scanner s = new Scanner(outputString);
                                      System.out.println(outputString.length()); // output is 4
                                      System.out.println(s.next().length()); //output is 3, not considering the space
                                      //char letter = s.next().charAt(i);
                                      //System.out.println(letter);
                                      }








                                      share|improve this answer
























                                        0












                                        0








                                        0






                                        You should follow the above solution for getting repeated characters in a string. However, I will just give you a hint about why you are getting the exception



                                        consider the following code:






                                        String outputString = "Pre ";
                                        for (int i = 0; i < outputString.length(); i++) {
                                        Scanner s = new Scanner(outputString);
                                        System.out.println(outputString.length()); // output is 4
                                        System.out.println(s.next().length()); //output is 3, not considering the space
                                        //char letter = s.next().charAt(i);
                                        //System.out.println(letter);
                                        }








                                        share|improve this answer












                                        You should follow the above solution for getting repeated characters in a string. However, I will just give you a hint about why you are getting the exception



                                        consider the following code:






                                        String outputString = "Pre ";
                                        for (int i = 0; i < outputString.length(); i++) {
                                        Scanner s = new Scanner(outputString);
                                        System.out.println(outputString.length()); // output is 4
                                        System.out.println(s.next().length()); //output is 3, not considering the space
                                        //char letter = s.next().charAt(i);
                                        //System.out.println(letter);
                                        }








                                        String outputString = "Pre ";
                                        for (int i = 0; i < outputString.length(); i++) {
                                        Scanner s = new Scanner(outputString);
                                        System.out.println(outputString.length()); // output is 4
                                        System.out.println(s.next().length()); //output is 3, not considering the space
                                        //char letter = s.next().charAt(i);
                                        //System.out.println(letter);
                                        }





                                        String outputString = "Pre ";
                                        for (int i = 0; i < outputString.length(); i++) {
                                        Scanner s = new Scanner(outputString);
                                        System.out.println(outputString.length()); // output is 4
                                        System.out.println(s.next().length()); //output is 3, not considering the space
                                        //char letter = s.next().charAt(i);
                                        //System.out.println(letter);
                                        }






                                        share|improve this answer












                                        share|improve this answer



                                        share|improve this answer










                                        answered Nov 11 at 15:48









                                        Subhasish Bhattacharjee

                                        7511




                                        7511























                                            0














                                            First of all, you shold not create new Scanner each time when you ready next character. Do it only once, before for loop.



                                            Second - to read scanner character by character, you have set delimeter as "". In this case, scan.next() returns next character.



                                            Third - you use Scanner to analyze string, that's OK (not optimal and overhead, but OK). Then do create new Scanner isntance and rely on it's data, but not on length of the goven string; do use Scanner.hasNext() method. I mean that all you need, is just add hasNext() to be sure that more characters exists in the scanner's stream:



                                            try (Scanner scan = new Scanner(outputString)) {
                                            scan.useDelimiter(""); // to make scan.next() return one single character

                                            while (scan.hasNext()) {
                                            char ch = scan.next().charAt(0); // next() returns String with one character
                                            // do your work
                                            }
                                            }


                                            P.S. This is code examples, how you can cound character frequencey in the given string with different ways. Probably, one of them you'll find more relevant to your task.



                                            // this is your approach
                                            public static int characterFrequency(String str, char ch) {
                                            try (Scanner scan = new Scanner(str)) {
                                            scan.useDelimiter("");
                                            int count = 0;

                                            while (scan.hasNext())
                                            count += scan.next().charAt(0) == ch ? 1 : 0;

                                            return count;
                                            }
                                            }

                                            // this one is the most efficient
                                            public static int characterFrequency(String str, char ch) {
                                            int count = 0;

                                            for (int i = 0; i < str.length(); i++)
                                            count += str.charAt(i) == ch ? 1 : 0;

                                            return count;
                                            }

                                            // this one is the smallest of code
                                            public static int characterFrequency(String str, char ch) {
                                            return (int)str.chars().filter(e -> e == ch).count();
                                            }





                                            share|improve this answer




























                                              0














                                              First of all, you shold not create new Scanner each time when you ready next character. Do it only once, before for loop.



                                              Second - to read scanner character by character, you have set delimeter as "". In this case, scan.next() returns next character.



                                              Third - you use Scanner to analyze string, that's OK (not optimal and overhead, but OK). Then do create new Scanner isntance and rely on it's data, but not on length of the goven string; do use Scanner.hasNext() method. I mean that all you need, is just add hasNext() to be sure that more characters exists in the scanner's stream:



                                              try (Scanner scan = new Scanner(outputString)) {
                                              scan.useDelimiter(""); // to make scan.next() return one single character

                                              while (scan.hasNext()) {
                                              char ch = scan.next().charAt(0); // next() returns String with one character
                                              // do your work
                                              }
                                              }


                                              P.S. This is code examples, how you can cound character frequencey in the given string with different ways. Probably, one of them you'll find more relevant to your task.



                                              // this is your approach
                                              public static int characterFrequency(String str, char ch) {
                                              try (Scanner scan = new Scanner(str)) {
                                              scan.useDelimiter("");
                                              int count = 0;

                                              while (scan.hasNext())
                                              count += scan.next().charAt(0) == ch ? 1 : 0;

                                              return count;
                                              }
                                              }

                                              // this one is the most efficient
                                              public static int characterFrequency(String str, char ch) {
                                              int count = 0;

                                              for (int i = 0; i < str.length(); i++)
                                              count += str.charAt(i) == ch ? 1 : 0;

                                              return count;
                                              }

                                              // this one is the smallest of code
                                              public static int characterFrequency(String str, char ch) {
                                              return (int)str.chars().filter(e -> e == ch).count();
                                              }





                                              share|improve this answer


























                                                0












                                                0








                                                0






                                                First of all, you shold not create new Scanner each time when you ready next character. Do it only once, before for loop.



                                                Second - to read scanner character by character, you have set delimeter as "". In this case, scan.next() returns next character.



                                                Third - you use Scanner to analyze string, that's OK (not optimal and overhead, but OK). Then do create new Scanner isntance and rely on it's data, but not on length of the goven string; do use Scanner.hasNext() method. I mean that all you need, is just add hasNext() to be sure that more characters exists in the scanner's stream:



                                                try (Scanner scan = new Scanner(outputString)) {
                                                scan.useDelimiter(""); // to make scan.next() return one single character

                                                while (scan.hasNext()) {
                                                char ch = scan.next().charAt(0); // next() returns String with one character
                                                // do your work
                                                }
                                                }


                                                P.S. This is code examples, how you can cound character frequencey in the given string with different ways. Probably, one of them you'll find more relevant to your task.



                                                // this is your approach
                                                public static int characterFrequency(String str, char ch) {
                                                try (Scanner scan = new Scanner(str)) {
                                                scan.useDelimiter("");
                                                int count = 0;

                                                while (scan.hasNext())
                                                count += scan.next().charAt(0) == ch ? 1 : 0;

                                                return count;
                                                }
                                                }

                                                // this one is the most efficient
                                                public static int characterFrequency(String str, char ch) {
                                                int count = 0;

                                                for (int i = 0; i < str.length(); i++)
                                                count += str.charAt(i) == ch ? 1 : 0;

                                                return count;
                                                }

                                                // this one is the smallest of code
                                                public static int characterFrequency(String str, char ch) {
                                                return (int)str.chars().filter(e -> e == ch).count();
                                                }





                                                share|improve this answer














                                                First of all, you shold not create new Scanner each time when you ready next character. Do it only once, before for loop.



                                                Second - to read scanner character by character, you have set delimeter as "". In this case, scan.next() returns next character.



                                                Third - you use Scanner to analyze string, that's OK (not optimal and overhead, but OK). Then do create new Scanner isntance and rely on it's data, but not on length of the goven string; do use Scanner.hasNext() method. I mean that all you need, is just add hasNext() to be sure that more characters exists in the scanner's stream:



                                                try (Scanner scan = new Scanner(outputString)) {
                                                scan.useDelimiter(""); // to make scan.next() return one single character

                                                while (scan.hasNext()) {
                                                char ch = scan.next().charAt(0); // next() returns String with one character
                                                // do your work
                                                }
                                                }


                                                P.S. This is code examples, how you can cound character frequencey in the given string with different ways. Probably, one of them you'll find more relevant to your task.



                                                // this is your approach
                                                public static int characterFrequency(String str, char ch) {
                                                try (Scanner scan = new Scanner(str)) {
                                                scan.useDelimiter("");
                                                int count = 0;

                                                while (scan.hasNext())
                                                count += scan.next().charAt(0) == ch ? 1 : 0;

                                                return count;
                                                }
                                                }

                                                // this one is the most efficient
                                                public static int characterFrequency(String str, char ch) {
                                                int count = 0;

                                                for (int i = 0; i < str.length(); i++)
                                                count += str.charAt(i) == ch ? 1 : 0;

                                                return count;
                                                }

                                                // this one is the smallest of code
                                                public static int characterFrequency(String str, char ch) {
                                                return (int)str.chars().filter(e -> e == ch).count();
                                                }






                                                share|improve this answer














                                                share|improve this answer



                                                share|improve this answer








                                                edited Nov 11 at 16:38

























                                                answered Nov 11 at 16:20









                                                oleg.cherednik

                                                5,49521017




                                                5,49521017






























                                                    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%2f53250205%2fusing-scanner-to-analyse-a-string-letter-by-letter-in-a-for-loop-throwing-ind%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







                                                    這個網誌中的熱門文章

                                                    Xamarin.form Move up view when keyboard appear

                                                    Post-Redirect-Get with Spring WebFlux and Thymeleaf

                                                    Anylogic : not able to use stopDelay()