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