2012-10-24 5 views
2

과제에 행맨 프로그램을 쓰고 있는데 작은 문제가있었습니다. 내 프로그램에서 단어를 분리하려면 '|'을 사용하고 있습니다. 상징. 예는이 단어를 추측 할 것입니다 :단어 사이에 구분 기호를 추가하는 방법은 무엇입니까?

U N I T E D | S T A T E S | O F | A M E R I C A 

나는 아무 표시하는 StringBuffer를 변수가 있습니다. '|'의 내가 구분 기호를 삽입하려면 다음 코드를 사용하려고

_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

여기 는 대시

if(guessword.indexOf('|') == -1) 
    System.out.print(" "); 
else 
    guessit.setCharAt(guessword.indexOf('|'),'|'); 

필자는 잘못 알고 있으며 단 하나의 구분 기호 만 삽입합니다. 구분 기호를 올바른 위치에 삽입 할 때 도와 주시겠습니까? 또한 System.out.print ("");를 제거하려고 할 수 있습니다. 불필요하게 공간을 남겨 둡니다. 휴식을 사용할 수 있습니까? 대신 위의 예를 들어 내가 실제로

public static void main()throws IOException 
{ 
    Hangman obj = new Hangman(); 
    InputStreamReader isr = new InputStreamReader(System.in); 
    BufferedReader br = new BufferedReader(isr); 
    PrintWriter p = new PrintWriter(System.out,true); 

    p.println("Lets play HANGMAN"); 
    p.println(); 
    p.println("Enter your choice according to the following options.\n 
       NOTE: Words are related to the topics given below.\n 
       1. Sports\n2. Movies\n3. Computer\n4. Food\n5. Countries"); 
    p.println(); 
    int choice = Integer.parseInt(br.readLine()); 
    obj.clearScreen(); 
    String bothwordandclue[] = new String[2]; 

    if(choice == 1) 
     bothwordandclue = obj.Sports(); 
    else if(choice == 2) 
     bothwordandclue = obj.Movies(); 
    else if(choice == 3) 
     bothwordandclue = obj.Computers(); 
    else if(choice == 4) 
     bothwordandclue = obj.Food(); 
    else if(choice == 5) 
     bothwordandclue = obj.Countries(); 
    else 
     p.println("Wrong choice"); 

    int counter = 6; 
    String guessword = bothwordandclue[0]; 
    String wordclue = bothwordandclue[1]; 

    int lengthofword = (int)(Math.round(((double)guessword.length()/2))); 
    int checkguess = 0; 
    String a; 
    StringBuffer guessit = new StringBuffer(); 

    for (int i = 0;i < lengthofword; i++) 
     guessit = guessit.append("_ "); 

    guessit.delete((2 * lengthofword)-1,(2 * lengthofword)); 

    if(guessword.indexOf('|') == -1) 
     System.out.print(" "); 
    else 
     guessit.setCharAt(guessword.indexOf('|'),'|'); 

    p.println(guessit); 
    do 
    { 
     p.println(); 
     p.println("Enter your guess letter in capitals"); 
     String guessletter = br.readLine(); 
     obj.clearScreen(); 

     for(int i = 0;i<lengthofword;i++) 
     { 
      if(guessletter.charAt(0) == guessword.charAt(2*i)) 
      { 
       guessit.setCharAt(2*i,guessletter.charAt(0)); 
       checkguess=1; 
      }     
     } 
     if(checkguess == 1) 
     { 
      p.println("Correct Guess"); 
      p.println(guessit); 
     } 
     else 
     { 
      counter--; 
      p.println("Wrong guess. You have " + counter + 
            " incorrect guesses left"); 
      p.println(guessit); 
     } 
     checkguess = 0; 
     a = guessit.toString(); 
     if(a.equals(guessword)) 
     { 
      p.println("You guessed the word!!!!!"); 
      counter=0; 
     }   
    }while(counter>0); 
} 

답변

1

당신은 indexOf 함께 할 수있는, 자바의 다른 내장 문자열 함수의 일부를 사용하거나 간단한 for 루프를 사용 할 수 있습니다. 그 방법의 다른 버전을 사용해야합니다.이 버전은 검색을 시작할 위치에서 위치를 취합니다. 여기에 필요한 String#indexOf(String str, int fromIndex)을 참조하십시오.

int index = guessword.indexOf("|"); 
while(index >= 0) { 
    guessIt.setCharAt(index, '|') 

    // Start searching for next "|" after this index 
    index = guessword.indexOf("|", index+1)); 
} 
+0

Upvote 문제가 내 것보다 효율적으로 해결 되었기 때문에 초보자에게는 분명하지 않습니다. http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String에 대한 링크가 포함되어있을 수 있습니다.html # indexOf (java.lang.String, int) –

+0

@PWhite. 물론 :) –

+0

고마워요. 이로 인해 문제가 매우 효과적으로 해결되었습니다. – crvineeth99

0

String.replaceAll

그리고 경우를 참조하십시오 다음과 같이

_ _ _ _ _ _ | _ _ _ _ _ _ | _ _ | _ _ _ _ _ _ _ 

내 주요 방법은 원하는

_ _ _ _ _ _ | _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

로 디스플레이를 얻을 정규식에 대해 모른다 :

|

Regular expression on wikipedia

Regular expression cheat sheet

+0

더 효율적이지만 초보자에게 정규 표현식을 배우라고하는 아이디어는 좋지 않습니다. –

+1

여기에 그 중 아무 것도 필요하지 않습니다. 왜 정규 표현식이 효과가 있다고 생각합니까? 우리는 다른 문자열을 기반으로하는 문자열의 문자를 대체합니다. –

+0

@PWhite 어휘가 있다면 언젠가 정규 표현식에 대해 배우게 될 것이라고 생각합니다. –

1

문제는 setCharAtindexOf 만이 첫 번째를 대체 왜 하나 개의 인덱스 각각에 적용한다는 것입니다. guessword을 여러 번 반복해야합니다. 당신은 즉

for(int i = 0; i < guessword.length(); i++){ 
    if(guessword.charAt(i) == '|') 
     guessit.setCharAt(i, '|'); 
} 
+0

게시물을 가져 주셔서 감사합니다. 질문을 게시하기 전에 이미이 문제를 시도했지만 단어 사이에 구분 기호를 넣지 않았습니다. D – crvineeth99

관련 문제