【发布时间】:2017-03-23 20:03:33
【问题描述】:
所以我正在尝试编写一个代码,提示用户使用基本计算器,或显示用户输入的给定句子中有多少单词的单词计数器,这是使用方法完成的。我已经弄清楚如何正确设置计算器,但是单词计数器给我带来了一些问题:
public static int wordCounter(String str){
String words[]=str.split(" ");
int count=words.length;
return count;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("What do you want to do( calculator(0)/word counter(1) )? ");
//This runs and I select '1' for word counter
int choice = input.nextInt(); //Input the choice here
if (choice == 0) {
// It runs this selection statment, and since zero is not selected,
//it runs the word Counter branch
calculator();
}else{
System.out.println("Please enter a sentence:"); // Tells me to enter a sentence
String sentence=input.nextLine();
//^ This input is completely skipped and goes
//right to the 'System.out.print(); Statement.
System.out.print("There are "+ wordCounter(sentence) + " words in the sentence.");
//^ This prints a 1 immediately after the branch is selected with '1'
}
}
我不确定哪里出了问题,因为这只发生在 if/else 语句中。做一些测试还告诉我,第一个扫描仪“int choice=input.nextInt()”似乎在某种程度上干扰了第二个扫描仪的字符串。任何保持类似格式的想法将不胜感激。
请原谅我的格式,它可能看起来不太好。
【问题讨论】:
-
计算器方法在哪里???
-
我没有包含它,因为该特定部分有效并且不是问题。如果你愿意,我可以包括它。
标签: java