-1
私は、スクラブルゲームをしているかのように、ランダムに与えられた文字を文字列の形で綴ることができるかどうかを調べるプログラムを書いています。私の問題は、任意の文字が無作為に与えられた文字に見つからない場合、それは私が何をするかをしなかったことです。ここ は、さらなる理解のために私のコードです:javaを使って単語が別の単語から綴られているかどうかを調べる
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());
}
それはタイプミスだように見えますし、文は!=
の代わりに==
を使うべきかどう:
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");
}
}
}
を "それは私がそれをやるように言われ何をしません" を参照してください。それどころか、あなたが言うことを正確にはしません。あなたはそれが何をすると思いましたか? –