I want to use the variable that is taken from the inputString() method into the countWords() method below, but I unfortunately run into errors when I try using the latter in the main() method. How do I work around this?
import java.util.*;
public class WordCounter {
public static String inputString(){
Scanner s = new Scanner(System.in);
System.out.println("\nInput your desired sentence/string: ");
String userInput = s.nextLine();
return userInput;
}
public static void countWords(int count, String userInput){
count = 1;
for (int i = 0; i < userInput.length() - 1; i )
{
if ((userInput.charAt(i) == ' ') && (userInput.charAt(i 1) != ' '))
{
count ;
}
}
System.out.print("Number of words in the sentence/string: " count);
}
public static void main (String [] args){
System.out.println("Word Counter.");
inputString();
countWords();
}
}
CodePudding user response:
- Capture the return value coming from your
inputString
method. - Pass that returned value to your
countWords
method.
Change this:
inputString();
countWords();
… to this:
String input = inputString();
countWords( input );
And it looks like count
in countWords
is supposed to be the result. So that should be returned to the calling method.
String input = WordCounter.inputString();
int count = WordCounter.countWords( input );
And alter your countWords
to return that value. Change the declared return type from void
to int
. Add a return
line at the end.
public static int countWords(int count, String userInput){
…
return count ;
}
Looking at the bigger picture, try to avoid static
as a student learning object-oriented programming.
Create multiple classes, where each class has one main responsibility. If we look at your business problem, we have three responsibilities:
- Business logic
- Interacting with user on the console.
- An app to run the show, with its
main
method.
And, by the way, the char
type has been essentially broken since Java 2, and legacy since Java 5. As a 16-bit value, it is physically incapable of representing most characters.
Instead, to work with individual characters, use code point integer numbers.
CodePudding user response:
This way your code should work
import java.util.Scanner;
public class WordCounter {
public static String inputString(){
Scanner s = new Scanner(System.in);
System.out.println("\nInput your desired sentence/string: ");
String userInput = s.nextLine();
return userInput;
}
public static void countWords(int count, String userInput){
count = 1;
for (int i = 0; i < userInput.length() - 1; i )
{
if ((userInput.charAt(i) == ' ') && (userInput.charAt(i 1) != ' '))
{
count ;
}
}
System.out.print("Number of words in the sentence/string: " count);
}
public static void main (String [] args){
System.out.println("Word Counter.");
String input = inputString();
countWords(0, input);
}
}