是的,這是作業,但我在尋求幫助。我已經閱讀了我們的書,並試圖與一羣人合作,並試着在這裏和其他地方在網上搜索。新手寫作方法 - 計算字符串中的單詞
我有這種工作。它要求輸入一個字符串兩次(應該只詢問一次),並且如果用戶輸入空白代碼,它似乎會給出錯誤消息。然而,它重複「你的字符串有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