-1
我正在写一个程序使用java,检查一个单词是否可以拼写从字符串形式的随机给定的字母,就像如果你正在玩一个可分级的游戏。我的问题是,如果在随机给定的字母中找不到任何字母,它就不会按照我所说的去做。 这是我做进一步的了解代码:使用java来检查一个单词是否可以拼写从另一个字
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");
}
}
}
_ “它没有做什么,我告诉它做” _相反,它确实完全符合你的要求。你期望它做什么? –