2016-08-13 2 views
2
import java.io.*; 

public class Page117 
{ 

    public static void main(String[] args) throws IOException 
    { 
     BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); 
     char letter; 
     String sentence; 
     int counter = 0; 
     char response = 'o'; 

     do 
     { 
      System.out.print("Type a sentence: "); 
      sentence = input.readLine(); 
      System.out.print("Type a character to find: "); 
      letter = (char) input.read(); 

      for(int x=0;x<sentence.length();x++) 
      { 
       if(letter==sentence.charAt(x)) 
       { 
        counter++; 
       } 
      } 

      System.out.println("Number of times " + letter + " occured is: " + counter); 
      System.out.print("Continue? [y/n]: "); 
      response = (char) input.read(); 

     }while(response != 'n');   
    }   
} 

프로그램 정보 : 사용자가 문장을 입력합니다. 사용자는 또한 문자를 입력하고 해당 문자 중 몇 개가 해당 문장에서 발생하는지 계산합니다.Java : Do-while loop '예 또는 아니요'응답

약간의 문제가 발생했습니다. 프로세스가 끝나면 내 응답을 입력 할 수 있도록 어떻게 만들 수 있습니까? 왜냐하면 내가 성격을 입력하고 나에게 사건의 횟수를 알려 주면 그 사건이 종료되거나 아무 것도 입력하지 않기 때문입니다.

나는 내 코드에서 거의 모든 것을 시도했다. do-while 루프는별로 사용하기 힘듭니다. 나는 그다지 많은 양을 사용하지 않는다.

+1

힌트 : 당신이 대답 할 때 "찾을 문자를 입력 :"당신은 아마 일부 문자를 입력하고 [돌아 가기] 공격이 반환 사실에 끝 (end-of-line) 문자이다, HTTPS 참조 : // ideone. com/ePYWSE 참고 : '스캐너'를 사용해야합니다 –

+0

대화 형 입력에서 읽는 것이 가장 좋습니다. 스캐너를 사용하는 것이 좋습니다. 내 의심은, 만약 당신이 타이프하고 타이프하고, 문장에서 프로그램 문자 t와 캐리지 리턴을 가지면, 결국 캐리지 리턴이 응답으로 읽히고''n ''과 비교됩니다. . 디버거 또는 일부 임시 System.out.println() 문을 사용하여 이러한 가정을 확인할 수 있습니다. –

+0

각 실행에 대해 * counter * 변수를 지우지 않으므로 발생 횟수도 잘못되었습니다. – 0x23212f

답변

2

직면하는 문제는 제공되는 문자가 여러 개인 경우 한 문자를 읽는 것과 관련이 있습니다. 입력 문자 + 캐리지 리턴.

그래서 간단하게 이런 식으로이

letter = (char) input.read(); 

교체 :

letter = input.readLine().charAt(0); 

가 실제로 readLine()를 호출하면 독자가 전체 라인을 읽을 것 (캐리지 리턴 포함) 및 반환 금액 만 여기에 입력 된 문자에 해당하는 줄 끝 부분 앞에 있어야합니다.

1

대신 스캐너를 사용할 수 있습니다. 다음 코드는 입력을 의도 한대로 기다립니다. 또한 당신은 아마 새로운 문장에 대한 카운터를 재설정 할 :

Scanner input = new Scanner(System.in); 

char letter; 
String sentence; 
int counter = 0; 
char response = 'o'; 

do 
{ 
    counter = 0; // reset the counter for a new sentence 

    System.out.print("Type a sentence: "); 
    sentence = input.nextLine(); 
    System.out.print("Type a character to find: "); 
    letter = (char) input.nextLine().charAt(0); 

    for(int x=0;x<sentence.length();x++) 
    { 
     if(letter==sentence.charAt(x)) 
     { 
      counter++; 
     } 
    } 
    System.out.println("Number of times " + letter + " occured is: " + counter); 
    System.out.print("Continue? [y/n]: "); 
    response = (char) input.nextLine().charAt(0); 

}while(response != 'n'); 

input.close(); 
2

@Ole V.V이 권리입니다. 첫 번째 입력 후 사용자가 입력 한 캐리지 리턴은 루프의 끝에서 읽혀집니다. 아래 코드가 작동합니다. 또한 카운터는 루프 내에서 초기화되어야합니다.

public class Page117 { 

    public static void main(String[] args) throws IOException 
    { 
     BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); 
     char letter; 
     String sentence; 

     do 
     { 
      int counter = 0; 
      char response = 'o'; 
      System.out.print("Type a sentence: "); 
      sentence = input.readLine(); 
      System.out.print("Type a character to find: "); 
      letter = input.readLine().charAt(0); 

      for(int x=0;x<sentence.length();x++) 
      { 
       if(letter==sentence.charAt(x)) 
       { 
        counter++; 
       } 
      } 

      System.out.println("Number of times " + letter + " occured is: " + counter); 
      System.out.print("Continue? [y/n]: "); 

     }while(input.readLine().charAt(0) != 'n'); 

    } 
}