The WordCruncher class Write the Java code for the class WordCruncher. Include t
ID: 3834997 • Letter: T
Question
The WordCruncher class
Write the Java code for the class WordCruncher. Include the following members: A default constructor that sets the instance variable 'word' to the string "default". A parameterized constructor that accepts one String object as a parameter and stores it in the instance variable. The String must have no whitespace and no punctuation. If the String parameter has whitespace or punctuation, set the instance variable to the string "default" instead. (This restriction will make your work on some of the following methods much easier.) A method String toString() that returns the instance variable. A method int numLetters() that returns the number of letters in the instance variable.
Write a class named WordCruncherTest that has only a main method that: asks the user for a word with the option to enter the word "quit" to quit creates a WordCruncher object that contains this word (unless the word is "quit") and then: outputs the number of letters in this object.
Explanation / Answer
########
public class WordCruncher {
private String word;
private boolean isValid(String str){
for(int i=0; i<str.length(); i++){
if(!Character.isLetter(str.charAt(i)) && !Character.isDigit(str.charAt(i)))
return false;
}
return true;
}
public WordCruncher() {
word = "default";
}
public WordCruncher(String str){
if(isValid(str)){
word = str;
}else
word = "default";
}
public int numLetters(){
int count = 0;
for(int i=0; i<word.length(); i++){
if(Character.isLetter(word.charAt(i)))
count++;
}
return count;
}
@Override
public String toString() {
return word;
}
}
#############
import java.util.Scanner;
public class WordCruncherTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String line;
WordCruncher obj;
System.out.println("Enter words(quit to stop) ? ");
line = sc.nextLine();
while(!line.trim().equalsIgnoreCase("quit")){
obj = new WordCruncher(line);
System.out.println("Number of letters: "+obj.numLetters());
line = sc.nextLine();
}
sc.close();
}
}
/*
Sample run:
Enter words(quit to stop) ?
pravesh
Number of letters: 7
this is the go
Number of letters: 7
nj
Number of letters: 2
mds fmwf 34r
Number of letters: 7
quit
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.