3. Develop an application that accepts a word from the user and calculates and outputs the number of letters in the word. The application should check that only one word was entered. If more than one word was entered, the application should output a message to the user and repeat to allow them to enter the word again. The application should make use of instantiable classes. Name the instantiable class Word.java.
时间: 2023-11-27 11:50:27 浏览: 93
Python库 | flask_accepts-0.16.5.tar.gz
Here is the Word.java class that can be used to develop the application:
```
public class Word {
private String word;
public void setWord(String word) {
this.word = word;
}
public int getLength() {
return word.length();
}
public boolean isSingleWord() {
return word.trim().split("\\s+").length == 1;
}
}
```
The `Word` class has three methods:
- `setWord(String word)` sets the user input as the word to be processed
- `getLength()` calculates and returns the number of letters in the word
- `isSingleWord()` checks if the user input is a single word
Here is an example of how to use the `Word` class in the application:
```
import java.util.Scanner;
public class WordApplication {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Word word = new Word();
while (true) {
System.out.print("Enter a word: ");
String userInput = input.nextLine();
word.setWord(userInput);
if (word.isSingleWord()) {
System.out.println("The word has " + word.getLength() + " letters.");
break;
} else {
System.out.println("Please enter only one word.");
}
}
input.close();
}
}
```
The `WordApplication` class uses a `Scanner` object to read user input and creates an instance of the `Word` class. It then uses a `while` loop to repeatedly prompt the user to enter a single word until a valid input is received. Once a valid input is received, the application uses the `Word` object to calculate and output the number of letters in the word, and then terminates.
阅读全文