2

I'm doing a part of a program, where I should see the number of times the last character appears in JAVA.

The problem is that I am new with the use of Strings ( and only can use String ). Informing a bit I have seen that with equals I can compare Strings. And with substring I can select each of the letters one by one in a loop. The problem comes when I compile, that I go out of the index of the String. And I do not understand why, since I only get to .length - 1

    String aux;
    int cont = 0;

    aux = cadena.substring(cadena.length()-1);

    for (int i = 0; i < cadena.length()-1; i++) {
        if(cadena.substring(i,1).equals(aux)) {
            cont++;
        }
    }

java.lang.StringIndexOutOfBoundsException: String index out of range:-1

In this line

if(cadena.substring(i,1).equals(aux))

acruma
  • 318
  • 2
  • 17
  • use `charAt` instead of `substring` and make `aux` a `char`, if that's permitted. Or, even better, see [this](https://stackoverflow.com/a/8910767/133203) answer. – Federico klez Culloca Nov 09 '18 at 08:05

2 Answers2

1

what you have done is like "Hello".substring(3, 1)

substring method takes two arguments startIndex and endIndex. so end index should always be greater than start index.

In cadena.substring(i,1), the value of i will go from 0 to cadena.length()-2, because of condition i<cadena.length()-1

  • Thanks to your answer. I found my error. You say me "startIndex and endIndex" then i think that i can change "cadena.substring(i,1)" for > "cadena.substring(i,i+1)" . Then im taking only the next one. Right? And i change too "i < cadena.length()-1" for > "i < cadena.length()" – acruma Nov 09 '18 at 08:15
  • you can use charAt(i) method in string, that will be more convenient when you are deling with characters – Deepak Gunasekaran Nov 09 '18 at 08:20
0

You can do something like this:

int count = 0;

char lastChar = cadena.charAt(cadena.length()-1);

for (int i = 0; i < cadena.length()-1; i++) {
   if(lastChar==cadena.charAt(i)) count++;
}
Tran Ho
  • 1,442
  • 9
  • 15