2013-11-03 1 views
0

여기서는 문자열을 별도의 단어로 분리 한 다음 모음이 포함되어있는 경우 각 단어의 끝에 "ay"을 추가하지만 문제는 마지막 단어에 도달했을 때입니다. indexOf-1이므로 내 if 문으로 자동 건너 뜁니다. 이 문제를 해결하기 위해 if (i ==-1)을 추가하려고 시도했지만 디버거를 사용하여 자동으로이 if 문을 건너 뜁니다. 왜 아무도 알지 못해? 어떻게이 문제를 해결하고, 마지막 단어에 "ay"을 추가 할 수 있습니다 경우에도 .indexOf is -1.indexOf "-1"은 if 문에서 건너 뜁니다.

방법 :

public static void pigLatin(String sentence){ 
    sentence = sentence.trim(); 

    if(sentence.length()> 0){ 
     int i = sentence.indexOf(" "); 
     String word = sentence.substring(0, i); 
     if(i == -1){ //this if statement is ignored 
      if (word.contains("a") || word.contains("i") || word.contains("o") || word.contains("e") || word.contains("u")){ 
       System.out.println(word + "ay"); 
      } else{ 
       System.out.println(word); 
      } 
     } 
     if(i != -1){ 
      if(word.contains("a") || word.contains("i") || word.contains("o") || word.contains("e") || word.contains("u")){ 
       System.out.println(word + "ay"); 
       pigLatin(sentence.substring(i)); 
      } else if(!word.contains("a") || !word.contains("i") || !word.contains("o") || !word.contains("e") || !word.contains("u")){ 
       System.out.println(word); 
       pigLatin(sentence.substring(i)); 
      } 
     } 
    } 
} 

홈페이지 :

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

문제를 나타내는 입력 예제를 제공해 줄 수 있습니까? – Keppil

답변

2

나는 두 가지 문제를 참조하십시오.

  • pigLatin(sentence.substring(i))pigLatin(sentence.substring(i+1)) 말을해야한다고 두 라인 - 그렇지 않으면 당신은 단지 반복해서 같은 공간을 참조하십시오.
  • else if(!word.contains("a") || ...은 단지 else이라고 할 수 있지만, 전체 작성을 고집하는 경우 ||이있는 &&을 사용해야합니다.
+0

이것은 문제에 답하지 않습니다 ... –

+0

예. 계속해서 같은 공간을 계속해서 말하면 (첫 번째 글 머리 부분만큼), 나는 결코 "i == - 1"이되지 않을 것입니다. –