ユーザー入力のうちの一つの単語を印刷する方法

Ouzanの:

どのように私はJavaでのユーザー入力のうちの一つの単語をプリントアウトできますか?例:ユーザーの入力:「我々は彼女が最善であるお母さんが大好きです」。なぜなら、最初と最後の文字の「お母さん」を印刷すると仮定したプログラムは同じです。私のコードは最後に何も印刷されません。ここに私のコードは次のとおりです。

      Scanner s = new Scanner(System.in);
        System.out.println("Please enter a Sentence");
        String input=s.nextLine();
        String builderString=" ";
        for(int i=0,j=0;i<input.length();i++){
            if(input.charAt(i)==' '){
                j=i+1; //upper the value of J if there is space (J will always check first char)
                if (input.charAt(j)==input.charAt(i)&&j<i) {//an if statement to check for match chars.
                        builderString=" "+input.charAt(i);// insert the char into a new string to print it in the console.
                    }
                }
            }
        }
        System.out.println(builderString);
    }
}
ニコラス:

むしろ文字列のすべての文字を解析するよりも、あなたは、単語の配列にあなたの入力を分割して個別に各単語をチェックすることができます。

あなたのループを保つことができますが、あればあなただけをチェックする必要がchart at 01つのと同じですword.length() - 1

ここでは実施例です。私はそれは私が使用している遊び場で動作するようにスキャナ部を削除したことに注意してください。

// This would be de equivalent of your scanner
String input = "We love mom she is the best";


String[] words = input.split(" ");
String output = "";
for(int i=0;i<words.length; i++){
   String currentWord = words[i];
   if(currentWord.charAt(0) == currentWord.charAt(currentWord.length() -1)) {
       output = currentWord;
    }
}   

System.out.println(output);   

また、あなたの必要はありません。jこれ以上の変数を。

あなたはそれをテストすることができ、ここで

おすすめ

転載: http://10.200.1.11:23101/article/api/json?id=478717&siteId=1