사용자 입력의 하나의 단어를 인쇄하는 방법

Ouzan의 :

내가 어떻게 자바에서 사용자 입력의 하나의 단어를 인쇄합니까? 예 : 사용자 입력 : "우리는 그녀가 최고 엄마 사랑 해요". 때문에 첫 번째와 마지막 문자의 "엄마"를 인쇄하는 가정 프로그램은 동일합니다. 내 코드는 마지막에 아무것도 인쇄되지 않습니다. 여기 내 코드는 다음과 같습니다

      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 0에서보다 동일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=478715&siteId=1