Reputation: 1
I am using contains to see if String (A) can generate String(B) (both taken from the user)
package trabajogrupal;
import java.util.Scanner;
public class TrabajoGrupal {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
char resp1 = 's';
String resp2 = "";
while (resp1 == 's') {
System.out.println("Ingrese la primer cadena ");
String cadena = in.nextLine().toLowerCase();
System.out.println("Ingrese la segunda cadena ");
String cadena1 = in.nextLine().toLowerCase();
if (cadena.contains(cadena1)) {
System.out.println("La cadena " + cadena + " puede generar la cadena " + cadena1);
} else {
System.out.println("La cadena " + cadena + " no puede generar la cadena " + cadena1);
}
System.out.println("Desea continuar ");
resp2 = in.nextLine();
resp2 = resp2.toLowerCase();
resp1 = resp2.charAt(0);
}
}
}
the first string should contain the second string but what happens is that it keeps getting in the else statement. Why?
Upvotes: 0
Views: 79
Reputation: 3106
You could check if you can make String B with String A's characters than you could do it like this:
System.out.println("First string");
String firstInput = geek.nextLine().toLowerCase();
System.out.println("Second string");
String secondInput = geek.nextLine().toLowerCase();
char[] secondInputCharacters = secondInput.toCharArray();
boolean contains = true;
for(int i = 0; i < secondInputCharacters.length; ++i)
{
if(firstInput.indexOf(secondInputCharacters[i]) < 0)
contains = false;
}
What this does is:
Upvotes: 0
Reputation: 3113
You may try flushing the input before taking it, so that if there are extra characters like newline, (\n) they are ignored
Upvotes: 0
Reputation: 651
Step though all characters in string B and check if the character is in string A.
Do this by using A.indexOf(each character in B). As long as it don't return - 1 the character is in string A.
Upvotes: 1