是的,这是作业,但我在寻求帮助。我已经阅读了我们的书,并试图与一群人合作,并试着在这里和其他地方在网上搜索。新手写作方法 - 计算字符串中的单词
我有这种工作。它要求输入一个字符串两次(应该只询问一次),并且如果用户输入空白代码,它似乎会给出错误消息。然而,它重复“你的字符串有1个单词,你的字符串有2个单词,你的字符串有3个单词,你的字符串有4个单词,你的字符串有5个单词。”然后再重复一次 - 不管这个字符串有多少个单词。我无法弄清楚我做错了什么,并感谢任何帮助。
/*
* Lab07a.java
*
* A simple program that computes the number of words in an input string.
* Used to practice breaking code up into methods.
*
* @author ENTER YOUR NAMES HERE
*
*/
package osu.cse1223;
import java.util.Scanner;
public class Lab07a {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in); //get scanner//
getInputString(keyboard);
String input = getInputString(keyboard);
int count = getWordCount(input);
}
// Given a Scanner, prompt the user for a String. If the user enters an empty
// String, report an error message and ask for a non-empty String. Return the
// String to the calling program.
private static String getInputString(Scanner keyboardScanner) {
System.out.print("Enter a string: ");
String str = keyboardScanner.nextLine();
if (str.length() ==0)
{
System.out.print("ERROR - string must not be empty");
}
return str;
}
// Given a String return the number of words in the String. A word is a sequence of
// characters with no spaces. Write this method so that the function call:
// int count = getWordCount("The quick brown fox jumped");
// results in count having a value of 5. You will call this method from the main method.
// For this assignment you may assume that
// words will be separated by exactly one space.
private static int getWordCount(String str) {
int spaces = 0;
int i = 0;
while (i <str.length())
{
char ch = str.charAt(i);
if (ch == ' ')
i++;
{
spaces++;
System.out.print("Your string has " + spaces + "words in it.");
}
}
return spaces;
}
}
你难道没有str.partition(蟒蛇)的等效使它会返回包含分隔符(空间在内)的分割字符串数组,然后您只需将str.split的长度与str进行比较。分区和区别是空格的数量。 – 2014-10-11 17:40:22
尝试所有= text.split(“”,-1),它似乎是str.partition等价物,并与words = text.split()进行比较。所以最后,空格= len(全部) - len(单词),这是主意。 – 2014-10-11 17:44:57
可能依赖于问题规范,但如果我分配了这个,我会寻找学生解决问题,并且会特别禁止使用现有的函数来解决问题。 “不要使用Java的分割功能 - 我希望你自己做。” – 2014-10-11 17:50:43