我一直在尋找,我找不到任何地方如何使用3種方法編寫字數。這是目前代碼的樣子。我迷失在如何使用這些方法。我可以做到這一點,而不使用不同的方法,只使用一種。請幫忙!!!使用方法編寫代碼來查找字符串中的字數
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.print("Enter a string: ");
String s = in.nextLine();
if (s.length() > 0)
{
getInputString(s);
}
else
{
System.out.println("ERROR - string must not be empty.");
System.out.print("Enter a string: ");
s = in.nextLine();
}
// Fill in the body with your code
}
// 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(String s) {
int count = getWordCount();
while (int i = 0; i < s.length(); i++)
{
if (s.charAt(i) == " ")
{
count ++;
}
}
getWordCount(count);
// Fill in the body
// NOTE: Do not declare a Scanner in the body of this method.
}
// 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 input) {
// Fill in the body
}
}
編輯: 我已經改變了代碼
private static String getInputString(String s) {
String words = getWordCount(s);
return words.length();
}
private static int getWordCount(String s) {
return s.split(" ");
}
但我不能得到字符串轉換爲整數。
看起來像你使用罰款,你用的方法有什麼問題的方法呢? – Stephan
可以在這裏提出具體的問題,但我們不會做你的功課。請在您嘗試過的方式以及卡住的地方非常清楚。 –
'if(s.charAt(i)==「」)'將始終爲假,因爲您在詢問char是否與String相同。 ''''代表空格作爲字符 – Edd