-2

I have a problem in my code, where I asked to find the number of occurrences of a character in a String, but I kept having an Exception errors and I don't know why? Here is my code:

import java.io.IOException;
import java.util.*;
import java.lang.*;

public class LabOne1 {

  public static void main(String[] args) throws IOException {
    
    Scanner scan = new Scanner(System.in);
    
    System.out.print("Enter a string: ");
    String strUser = scan.next().toLowerCase();
    
    System.out.print("Enter a character: ");
    char charUser = (char) System.in.read();
    Character.toLowerCase(charUser);
    
    System.out.print(charUser + "occurs " + count(strUser, charUser) +
            " times in the string " + strUser);
  }

  public static int count(String str, char a){
    
    int counter = 0;
    
    for(int i = 0; i <= str.length(); i++){
        if (str.charAt(i) == a){
            
            counter++;
        }
    }
    
    return counter;
  }
}

Update: The issue is in the loop as the iterator should be higher than zero instead of equal or higher.

for(int i = 0; i < str.length(); i++)
Rayan
  • 105
  • 1
  • 7
  • 1
    We aren't a debugging service. Once you've found the problem code, ask a *specific* question. – Andrew Li Jul 05 '16 at 19:01
  • 1
    We don't know why you're getting exceptions either. We also don't how what exceptions you're getting, or where in the code they are being generated, or the input you are entering that results in them, or any of the other information you haven't provided us. – azurefrog Jul 05 '16 at 19:07
  • 1
    What they mean is, please include the stacktrace of the exception that you're asking about. – erickson Jul 05 '16 at 19:15
  • 1
    Please note that you will not be able to process sentences with your code. Only single words – Rabbit Guy Jul 05 '16 at 19:16
  • Let me give you a hint. You are getting a Out of Bounds Exception, which usually means you are iterating over your string. modify your loop bounds – Ambidextrous Jul 05 '16 at 19:17
  • The previously suggested duplicate is *not* a duplicate. The exception isn't even the same type. – erickson Jul 05 '16 at 19:22
  • I agree with you, it was my bad that I included the whole code instead of the portion that had the error when I debugged. – Rayan Jul 06 '16 at 22:46

1 Answers1

3

Your string indexing is incorrect. Valid indexes are between 0, inclusive, and str.length() exclusive. Your loop can work like this:

for(int i = 0; i < str.length(); i++) {
  if (str.charAt(i) == a) counter++;
}

Alternatively, you can do something like this:

int count = Math.toIntExact(str.chars().filter(ch -> ch == a).count());
erickson
  • 265,237
  • 58
  • 395
  • 493
  • Thank you so much, it worked, and it's indeed that my indexes did exceeded the length of the String. – Rayan Jul 06 '16 at 22:50