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

を "それは私がそれをやるように言われ何をしません" を参照してください。それどころか、あなたが言うことを正確にはしません。あなたはそれが何をすると思いましたか? –

答えて

0

if/else見てみましょう。


あなたが直接この値を返すことで、物事を簡単に作ることができます:

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

.....ありがとう、あなたは完璧に働いています。 –

関連する問題