我一直在寻找,我找不到任何地方如何使用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