Я искал и не могу найти нигде, как написать число слов, используя 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
}
}
EDIT: Я изменил код
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