Can someone help me with writing an application that counts the words in a Strin
ID: 3764493 • Letter: C
Question
Can someone help me with writing an application that counts the words in a String entered by a user. Words are seperated by any combination of spaces, periods, commas, semicolons, question marks, exclamation points, or dashes. Save the file as CountWords.Java This problem is in Java Programming 7th Edition, by Joyce Ferrell Page 338 Problem #5
Here's what i have so far but my question is what do i modify to make it run:
public class Countwords
{
public static void main(String[] args)
{
String aString = "Hello. Jane. How are you??
int numwords = 0;
int stringLength = aString.length();
System.out.print(ch);
for (int i = 0; i < stringLength; i++)
{if (aString.charAt(i) != ' ', aString.charAt (i) != '.', aString.charAt (i) != ','
aString.charAt(i) != ';', aString.charAt (i) != '?', aString.charAt (i) != '!'
aString.charAt(i) != '-')
numOfChar++;
}
System.out.println();
System.out.println("The number of Words in the string is "
+ numwords);
}
Explanation / Answer
import java.util.Scanner;
/**
* @author srinu
*
*/
public class CountWords {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Enter a string: ");
String str = scanner.nextLine();// "Hello how are you? I am doing
// fine";
int count = countWords(str);
System.out.println("There are " + (count) + " words in the string");
} catch (Exception e) {
// TODO: handle exception
} finally {
scanner.close();
}
}
/**
* @param str
* @return number of words in the string
*/
public static int countWords(String str) {
int count = 0;
boolean word = false;
char[] ch = str.toCharArray();
for (int i = 0; i < ch.length; i++) {
if (!(ch[i] == ' ')) {
for (int j = i; j < ch.length; j++, i++) {
if (!(ch[j] == ' ')) {
word = true;
if (j == ch.length - 1) {
count++;
}
continue;
} else {
if (word) {
count++;
}
word = false;
}
}
} else {
continue;
}
}
return count;
}
}
OUTPUT:
Enter a string: Hello. Jane. How are you??
There are 5 words in the string
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.