Reputation: 11
I am just getting introduced to methods in my MIS class, and I am having some trouble integrating the methods to work together. I need to create 3 separate methods that control the code. The object is to be able to either count the number of words in a sentence, or count the number of vowels in a word, the way that you switch between the methods is inputting a v, w, or q to quit. My code only spits out input from the main method, and I need it to reference the other methods to work properly. I don't know how to reference the other methods in my code. Can anyone tell me what I'm doing wrong? Thanks a lot guys!
The top method is my main method, the middle one is my word counting method, and the third is my vowel method.
import java.util.Scanner;
public class P7_MethodTester
{
public static void main(String[] args){
System.out.println("Enter v to count vowels, w to count words, and q to quit");
Scanner in = new Scanner(System.in);
System.out.print("Enter a letter: ");
String str = in.next();
while(str != "q")
{
if(str.equals("w")){
System.out.println("Please input your sentence: ");
String w = in.next();
System.out.println("You input " + countWords(str) + " words");
}
else if(str.equals("v")){
System.out.println("Please input your sentence: ");
String v = in.next();
System.out.println("You input " + countVowels(str) + "vowels");
}
else{
System.out.println("Program terminated");
}
}
}
public static int countWords(String w){
int wordCount = 0;
boolean word = false;
int endOfLine = w.length() - 1;
for (int i = 0; i < w.length(); i++) {
if (Character.isLetter(w.charAt(i)) && i != endOfLine) {
word = true;
} else if (!Character.isLetter(w.charAt(i)) && word) {
wordCount++;
word = false;
} else if (Character.isLetter(w.charAt(i)) && i == endOfLine) {
wordCount++;
}
}
return wordCount;
}
public static int countVowels(String v){
int vowels_count = 0;
for (int i = 0; i < v.length(); i++) {
char current_char = Character.toLowerCase(v.charAt(i));
if (current_char == 'a' || current_char == 'e' || current_char == 'o'
|| current_char == 'i' || current_char == 'u' || current_char == 'y') {
vowels_count += 1;
}
}
return vowels_count;
}
}
Upvotes: 0
Views: 73
Reputation: 16944
There are a number of things that come to question. Like do you want to evaluate the sentence as "w" or "q" or "v"
I suggest you instantiate a new Scanner
after the first.
while (!str.equals("q")) {
in = new Scanner(System.in);
This way you represent 2 entries. I would probably not use while
.
Also, look into using Scanner.nextLine()
for the whole sentence.
And finally, pass w
or v
not str
as arguments to countWords
and countVowels
.
You should think of the program as steps:
Upvotes: 1
Reputation: 29
Instead of calling the countWords and countVowels function with 'w' and 'v' you have passed str for both the functions
Upvotes: 1