JO_VIC JO_VIC - 3 months ago 9
Java Question

Using java to checking if a word can be spelt from another word

i'm writing a program using java that checks if a word can be spelt from random given letters in form of a string like if you were playing a scrable game. my problem is if any letter is not found in the random given letters it doesn't do what i told it to do.
Here is my code for further understanding:

public class Test {

public static void main(String[] args) {
canSpell("cenimatography","minato");

/* i get an error for the below, "**String index out of range:-1**"
instead of returning can't spell because 'o' is not present.
*/
canSpell("cenimatgraphy","minato");
}

//checks if a word can be spelt from string of letters
public static void canSpell(String letter, String word) {

boolean check=true;

for(int i=0;i<word.length();i++) {
if(letter.indexOf(word.charAt(i))!=-1) {
check = false;
} else {
int charLocation = letter.indexOf(word.charAt(i));
letter = letter.substring(0,charLocation)+letter.substring(charLocation+1,letter.length());
}
check = true;
}

if(check) {
System.out.println("it CAN spell");
} else {
System.out.println("it CANNOT spell");
}
}
}

Answer

Lets look at the if/else:

if(letter.indexOf(word.charAt(i)) != -1) { // The same as assignment of charLocation
    check = false;
} else {
    // charLocation will always be -1 here.
    int charLocation = letter.indexOf(word.charAt(i));
    // Causing the first substring to be out of range.
    letter = letter.substring(0,charLocation)+letter.substring(charLocation+1,letter.length());
 }

It looks like it's a typo, and the if statement should should use == instead of !=.


You could make things easier by directly returning this value:

public static boolean canSpell(String letter, String word) {
    for(int i=0;i<word.length();i++) {
         if(letter.indexOf(word.charAt(i)) == -1) { // <-- change to '=='
            return false;
         } else {
            int charLocation = letter.indexOf(word.charAt(i));      
            letter = letter.substring(0,charLocation)
                + letter.substring(charLocation+1,letter.length());
        }
    }

    return true;
}
if(canSpell("cenimatography","minato")) {
    System.out.println("it CAN spell");
} else {
    System.out.println("it CANNOT spell");
}

See Ideone

Comments