0

私の AP プロジェクトの 1 つに、各単語を文字列から分離することが含まれています。何度も達成しようとしましたが、成功しませんでした! 私のクラスはまだ配列、正規表現、または分割についてまだ学んでいないので、助けていただければ、それらのいずれかを避けてください。ただし、substring、charAt、indexOf、length、trim ... については学習しました。

これは私の試みの 1 つですN

public class Functions {
public static String stringReversal(String word){
    if (word.length() <= 1){
        return word;
    }else{
        char c = word.charAt(0);
        return stringReversal(word.substring(1)) + c;
    }
}

public static Boolean palindrome(String word){
    Boolean palindrome;
    if (word.equalsIgnoreCase(stringReversal(word))){
        return palindrome = true;
    } else{
        return palindrome = false;
    }
}

public static String pigLatin(String sentence){
    if(sentence.length() <= 1){
        return sentence;
    } else {
       String newWord = "";
       return newWord += pigLatin(sentence.substring(0, sentence.indexOf(" "))) + " N ";
    }
}

}

主要:

public class Main {
public static void main (String [] args){
    Scanner in = new Scanner(System.in);
    String word = in.nextLine();
    System.out.println(Functions.test(word));
   }
} 

ただし、出力は印刷のみNです。誰でも助けて、これを達成できる方法を教えてください。私は多くのアイデアを試しましたが、うまくいきませんでした。

4

3 に答える 3

0

これは非常に宿題に関連しているように見えるので、いくつかのヒントと提案のみを投稿します。私のヒントと提案を組み合わせて、自分で解決策を考え出す必要があります。

私はこれを信じています:これ sentence.indexOf("") であるべきです:sentence.indexOf(" ")

空の文字列の indexOf をチェックしてもあまり意味がありません (空の文字列は文字列内のどこにでもあるため、常に 0 を返します)。

public static void main(String[] args) {
    String word = "a bit of words";
    System.out.println(test(word));
}

public static String test(String sentence){
    if(sentence.length() <= 1){
        return sentence;
    } else {
        String newWord = "";
        return newWord += test(sentence.substring(0, sentence.indexOf(" "))) + " N ";
    }
}

上記のプリント:a N

ただし、入力が 1 単語のみの場合、sentence.indexOf(" ")-1 が返されます。これを確認する必要があります。提案: if ステートメントを変更して、代わりに文字列に空白文字が含まれているかどうかを確認します。

割り当てを解決するには、単語ごとにわずかに変更されたプロセスを繰り返すために、ある種のループ (再帰も一種のループである可能性があります) が必要です。ヒント: 最初の単語をフェッチしてから、抽出された単語を除いて元の文字列をフェッチします。

于 2013-11-02T01:44:24.290 に答える
0
public static void main( String[] args )
{
    Scanner in = new Scanner( System.in );
    try
    {
        while( true )
        {
            String word = in.nextLine();
            System.out.println( splitWords( word ) );
        }
    }
    finally
    {
        in.close();
    }

}

private static String splitWords( String s )
{
    int splitIndex = s.indexOf( ' ' );
    if( splitIndex >= 0 )
        return s.substring( 0, splitIndex ) + " N " + splitWords( s.substring( splitIndex + 1 ) );
    return s;
}
于 2013-11-02T02:04:31.397 に答える
-1

標準メソッド String#split() を使用できます

String[] words = sentence.split(' ');

単語よりも注意してください配列です

于 2013-11-02T01:53:20.390 に答える