2016-11-25 3 views
2

숙제를위한 프로그램을 쓰고 있는데, 메뉴를 사용하여 문자열을 수정해야합니다. 코드의 나머지 부분은 바인딩에서 나를 가진 한 부분을 제외하고는 잘 작동합니다. 문자열에서 단어와 모든 단어를 찾으려면 메서드를 사용하고 있습니다. 루프 외부에서이 메서드를 실행할 때마다 필요한 결과를 얻을 수 있지만 while 문이나 switch 문을 사용할 때마다 프로그램에서 아무 것도주지 않습니다. 메서드는 발생 횟수에 대해 int를 반환해야합니다. 다음은 해당 코드의 발췌 부분입니다.내 프로그램 방법에 아무 것도 출력하지 않습니다.

import java.util.Scanner; 

    public class test { 
    public static Scanner scnr = new Scanner(System.in); 

    public static int findWord(String text, String userText) { 
     int occurance = 0; 
     int index = 0; 

     while (index != -1) { 
      index = userText.indexOf(text, index); 
      if (index != -1) { 
       occurance++; 
       index = index + text.length(); 
      } 
     } 

     return occurance; 
    } 

    public static void main(String[] args) { 

     System.out.println("Enter a text: "); 
     String userText = scnr.nextLine(); 

     System.out.println("Enter a menu option"); 
     char menuOption = scnr.next().charAt(0); 

     switch (menuOption) { 
     case 'f': 
      System.out.println("Enter a phrase from text: "); 
      String text = scnr.nextLine(); 

      int occurance = (findWord(text, userText)); 

      System.out.println("" + text + " occurances : " + occurance + ""); 
      break; 
     default: 
      System.out.println("Goodbye"); 
     } 

     return; 
    } 
} 

이제 몇 가지 알아 챘습니다. 메서드 내부에있는 동안 사용자에게 프롬프트하면 switch 문 내부에서 println을 완료하기 위해 찾고 있던 텍스트가 아니라 정수를 반환합니다. 그리고 내가 switch 문 안에있는 단어에 대해 사용자에게 물어볼 때마다 나는 아무것도 얻지 못한다. 누구든지 나를위한 해결책이 있다면, 내가 간과하거나 실종 될 수있는 단서가 없기 때문에 나는 그것을 크게 감사 할 것입니다.

+0

코드 디버깅 방법을 알아보십시오. 그래서 무슨 일이 일어나고 있는지 알 수 있습니다. 어떤 이유로 텍스트는 빈 문자열로 읽히므로 루프는 끝나지 않습니다 (문자열 ""은 각 루프의 인덱스 0에 있습니다!). – Heri

+0

루프에서'next()'다음에'nextLine()'을 사용하고 있기 때문에 그 이유는 마지막 줄 바꿈을 사용하지 않기 때문에이 문제가 발생했기 때문일 수 있습니다. 이 스레드를 확인 했습니까? http : //stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo –

답변

0

char menuOption = scnr.next().charAt(0);char menuOption = scnr.nextLine().charAt(0);으로 변경해야합니다.

+0

ughhhh, thank youuuuuu – James

+0

죄송합니다, 내 나쁜, 알았다! – James

0

문제는 당신이 scnr.next()로 지속적으로 읽고있는 당신의 Scanner 방법으로하지만, 아래 그림과 같이 scnr.nextLine()`으로 변경해야합니다

또한
public static void main(String[] args) { 
     Scanner scnr = null; 
     try { 
      scnr = new Scanner(System.in); 

     System.out.println("Enter a text: "); 
     String userText = scnr.nextLine(); 

     System.out.println("Enter a menu option"); 
     char menuOption = scnr.nextLine().charAt(0); 

     switch (menuOption) { 
     case 'f': 
      System.out.println("Enter a phrase from text: "); 
      String text = scnr.nextLine(); 

      int occurance = (findWord(text, userText)); 

      System.out.println("" + text + " occurances : " + occurance + ""); 
      break; 
     default: 
      System.out.println("Goodbye"); 
     } 
     return; 
     } finally { 
      if(scnr != null) 
       scnr.close(); 
     } 
    } 

, 당신이 폐쇄되는 것을 보장 스캐너 개체가 finally 블록에 올바르게 있습니다.

관련 문제