11 Replies Latest reply on Oct 19, 2008 6:40 PM by 3004

    How to use the scanner class to ask for a character?

    843785
      Hey guys, this is my assignment:

      Ask the user for a single letter and a sentence, and print out the
      number of times that letter shows up in the sentence.

      Please tell me how to scan for a character. I tried this:
      import java.util.Scanner;
      
      public class Frequencies
      {
          public static final void main(String[] args)
          {
              Scanner scanner = new Scanner(System.in);
              Scanner scan = new Scanner(System.in);
              System.out.println("Enter a sentence");
              String x = scanner.next();
              System.out.println("Enter a letter to look for");
              String y = scan.next();
              char z = y.charAt(0);
              int chara = 0;
              for(int i = 0; i<x.length(); i++){
                      if(z==y.charAt(i)){
                              chara = chara++;
                      }
              }
              System.out.println("There are " + chara + " " + z + "s in the sentence");
          }
      }
      and got the error after Running (not compiling):
      Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
              at java.lang.String.charAt(String.java:687)
              at Frequencies.main(Frequencies.java:16)
      I thought this meant that I was asking for the character in postition 1 of string y, but in my code I wrote position 0

      when I tried inserting words in the character place (just to see what happened, not expecting functionallity, I got
      Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: [NUMBER OF CHARACTERS]
              at java.lang.String.charAt(String.java:687)
              at Frequencies.main(Frequencies.java:16)
      Please help.
      The assignment isn't due nor graded, this is just killing me lol.

      Thanks in advance

      Edited by: Sevan on Oct 18, 2008 4:40 PM
        • 1. Re: How to use the scanner class to ask for a character?
          843785
          I haven't run your code, but what if you replace scanner.next() with scanner.nextLine()? The latter will swallow the end of line character.
          • 2. Re: How to use the scanner class to ask for a character?
            843785
            Nope, my suggestion won't help. Your problem is using bad variable names, names that won't help you spot the error. Try these names instead and you'll see:
            import java.util.Scanner;
            
            public class Frequencies
            {
              public static final void main(String[] args)
              {
                Scanner scanner = new Scanner(System.in);
                Scanner scan = new Scanner(System.in);
                System.out.println("Enter a sentence");
                String sentence = scanner.next();
                System.out.println("Enter a letter to look for");
                String charString = scan.next();
                char charOfInterest = charString.charAt(0);
                int charCount = 0;
                for (int i = 0; i < sentence.length(); i++)
                {
                  if (charOfInterest == charString.charAt(i)) // see something wrong here?
                  {                               // perhaps the wrong variable being used?
                    charCount = charCount++;
                  }
                }
                System.out.println("There are " + charCount + " " + charOfInterest + "s in the sentence");
              }
            }
            Edited by: Encephalopathic on Oct 18, 2008 4:50 PM
            • 3. Re: How to use the scanner class to ask for a character?
              795402
              You can also re-use the Scanner object, there's no need to create a new one for each user input.

              And: "charCount = charCount++;" --> "charCount++;"
              • 4. Re: How to use the scanner class to ask for a character?
                843785
                oscarjustesen wrote:
                You can also re-use the Scanner object, there's no need to create a new one for each user input.
                And: "charCount = charCount++;" --> "charCount++;"
                yikes, i should have picked that up. Thanks for the catch.
                • 5. Re: How to use the scanner class to ask for a character?
                  843785
                  Thanks for all the help. I think I get it now!

                  I'm glad that you didn't just tell me to switch which string in my for loop
                  -It made me think a lot more and now I get it a lot more too!

                  Edited by: Sevan on Oct 19, 2008 9:53 AM
                  • 6. Re: How to use the scanner class to ask for a character?
                    843785
                    I didn't check to see if it did what it was supposed to.

                    Unfortunately, the number of characters is always 1 now.
                    import java.util.Scanner;
                    
                    public class Frequencies
                    {
                        public static final void main(String[] args)
                        {
                            Scanner scanner = new Scanner(System.in);
                            Scanner scan = new Scanner(System.in);
                            System.out.println("Enter a sentence");
                            String sentence = scanner.next();
                            System.out.println("Enter a letter to look for");
                            String charString = scan.next();
                            char charOfInterest = charString.charAt(0);
                            int charCount = 0;
                            for(int i = 0; i < sentence.length(); i++){
                                    if(charOfInterest == sentence.charAt(i)){
                                            charCount++;
                                    }
                            }
                            System.out.println("There are " + charCount + " " + charOfInterest
                    + "s in the sentence");
                        }
                    }
                    My guess is that the problem lies in the for loop.

                    Any ideas?
                    • 7. Re: How to use the scanner class to ask for a character?
                      3004
                      Sevan wrote:
                      I didn't check to see if it did what it was supposed to.

                      Unfortunately, the number of characters is always 1 now.
                      I suggest the following:

                      Add print statements to show...

                      * sentence
                      * charOfInterest
                      * which values it's comparing each time through the loop.

                      Also, read Scanner's docs more closely.
                      • 8. Re: How to use the scanner class to ask for a character?
                        843785
                        I've used this method for a while now and it gets the job done.
                        import java.util.Scanner;
                        public class ReadInput {
                              public static void main(String[] args) {
                                    Scanner UserInput = new Scanner(System.in);
                                    char letter = UserInput.findWithinHorizon(".", 0).charAt(0);
                              }
                        }
                        • 9. Re: How to use the scanner class to ask for a character?
                          3004
                          Skydev2u wrote:
                          I've used this method for a while now and it gets the job done.
                          import java.util.Scanner;
                          public class ReadInput {
                          public static void main(String[] args) {
                          Scanner UserInput = new Scanner(System.in);
                          char letter = UserInput.findWithinHorizon(".", 0).charAt(0);
                          }
                          }
                          I know you're trying to help, but this isn't really doing it. It does nothing to address the source of the OP's problem. The way he's doing it now is almost right. He just needs to do a tiny bit of detective work to fix a small bug. Tossing off a totally different approach, with no explanation, is not particularly helpful.
                          • 10. Re: How to use the scanner class to ask for a character?
                            843785
                            jverd wrote:
                            Skydev2u wrote:
                            I've used this method for a while now and it gets the job done.
                            import java.util.Scanner;
                            public class ReadInput {
                            public static void main(String[] args) {
                            Scanner UserInput = new Scanner(System.in);
                            char letter = UserInput.findWithinHorizon(".", 0).charAt(0);
                            }
                            }
                            I know you're trying to help, but this isn't really doing it. It does nothing to address the source of the OP's problem. The way he's doing it now is almost right. He just needs to do a tiny bit of detective work to fix a small bug. Tossing off a totally different approach, with no explanation, is not particularly helpful.
                            Your right jverd I skimmed the OP's problem too quick;y and in tern didn't understand it fully. After reading the post thoroughly I saw that the problem can be solved by taking the sentence the user enters and then converting it into a array of characters. Then searching for the specific letter the user enters is achieved by comparing it to each individual element of the char array. Then incrementing a counter variable each time a match is made. I hope this example code solve your problem.
                            /**
                             *
                             * @author skydev
                             */
                            import java.util.Scanner;
                            public class SentenceReader {
                                public static void main(String[] args) {
                                    int counter = 0; //Amount of time the letter appears in the sentence
                                    char letter;    //Letter the user search for
                                    char[] sentenceArray; //char array to hold the elements of the string the user inputs
                                    String sentence; //sentence the user inputs
                                    
                                    Scanner UserInput = new Scanner(System.in);
                                    System.out.println("Please enter a sentence! ");
                                    sentence = UserInput.nextLine();
                                    sentenceArray = sentence.toCharArray(); //splits up the users sentence into a array of char
                                    System.out.println("Please enter a letter to search for ");
                                    letter = UserInput.findWithinHorizon(".", 0).charAt(0);
                                     for(int i = 0; i < sentence.length(); i++){
                                            if(letter == sentenceArray){ //search to see if the letter of interest equals to each char (letter) of the array
                            counter++; //increments the amount of time the letter appears, set to 0 by default
                            }
                            }
                            System.out.println("The letter appeared " + counter + " times in the sentence"); //Displays the result :) I love programming

                            }
                            }
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            
                            • 11. Re: How to use the scanner class to ask for a character?
                              3004
                              Skydev2u wrote:
                              Your right jverd I skimmed the OP's problem too quick;y and in tern didn't understand it fully. After reading the post thoroughly I saw that the problem can be solved by taking the sentence the user enters and then converting it into a array of characters.
                              That's not a good solution either. You're overcomplicating it. And please do not give full code solutions.