Why do I get the total of the characters as a result?

1

The idea is to count the number of times a letter appears in a sentence; in this case it is b, but it gives me as a result the total of all the letters

    char x='b';
    String y="hola";

            int n=0;
            for(int i=0;i<y.length();i++) {
                if(y.charAt(i)==x);
                n++;

            }
            System.out.println(n);  
        }
    
asked by TGAB99 28.10.2018 в 18:24
source

2 answers

4

The problem is that you have a semicolon after the if, then the counter increases with each iteration. You should do something like this:

char x='b';
String y="hola";
int n=0; 
for(int i=0;i<y.length();i++) {
    if(y.charAt(i)==x)
        n++;
}
System.out.println(n); 

Good luck!

    
answered by 28.10.2018 в 19:31
-1

It occurs to me that you use the indexOf() method which will return

  • -1 if the indicated value does not exist in the string
  • If it exists, it returns the position in which the element is inside the array remember that the elements in the arrays begin with the value or index 0
  • EXAMPLE CODE

    public class MyClass
    {
        public static void main(String arags[])
        {
                char x='b';
                String y="hola";
                if(y.indexOf(x) == -1)
                {
                    System.out.println("La cadena no contiene el valor: "+x);
                }else{
                    System.out.println("La cadena si contiene el valor: "+x);
                }
        }
    }
    

    EXPLANATION

    Within the if we verify that the method indexOf() returns -1 if the element was not affirmed, it was not located and we printed a message

    On the other hand, if the value does exist, we print a different message

    EXAMPLE 2

    If you want the code to show you the location of the character within the array, if it exists in the; then your code could look like this

    public class MyClass
    {
        public static void main(String arags[])
        {
                char x='b';
                String y="hola";
    
               System.out.println(y.indexOf(x));
        }
    }
    

    What you will get for output in the console is: -1 if the value does not exist or otherwise it can be:

    | 0 | 1 | 2 | 3 | -> posiciones en el array
    -----------------
    | h | o | l | a | ->elemento por cada posición en el array
    
        
    answered by 28.10.2018 в 18:49