2016-08-15 50 views
-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"); 
     } 
    } 
} 
+4

_ “它没有做什么,我告诉它做” _相反,它确实完全符合你的要求。你期望它做什么? –

回答

0

让我们看看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()); 
} 

它看起来就像是一个错字,而if语句是应使用==,而不是!=


你可以让事情变得更容易通过直接返回这个值:

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"); 
} 

Ideone

+0

.....谢谢你的工作完美。 –

相关问题