2016-11-25 56 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

原因可能是因为您在循环中使用'nextLine()'后面的nextL()',因为后者不会消耗最后一个换行符,所以必须发生此问题。你有没有检查这个线程?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,谢谢youuuuuu – James

+0

哎呀,我的坏,得到它了! – James

0

问题是与你的Scanner方法,你与scnr.next()不断阅读,但是,如下图所示,应改为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区块中正确。