【发布时间】:2016-11-25 17:55:52
【问题描述】:
我正在编写一个家庭作业程序,我将使用菜单修改字符串。其余代码工作正常,除了一个让我陷入困境的部分。我正在使用一种方法来查找字符串中的单词及其所有出现。每当我在循环之外执行此方法时,我都会得到我需要的结果,但是每当我在 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 处找到!)。
-
原因可能是因为您在循环中使用
next()之后的nextLine()并且由于后者不使用最后一个换行符,所以一定会出现此问题。你检查过这个线程吗?stackoverflow.com/questions/13102045/…
标签: java methods switch-statement