- The Java Workshop
- David Cuartielles Andreas G?ransson Eric Foster Johnson
- 1313字
- 2021-06-11 13:05:21
Checking the Precedence of a Class with instanceof
You can check whether an object is an instance of a specific class. This can be convenient for things such as error checking, handling data in different ways depending on its precedence, and more. The following example shows the checkNumber method, which can discriminate between different types of variables and will print different messages based on that:
public class Example04 {
public static void checkNumber(Number val) {
if( val instanceof Integer )
System.out.println("it is an Integer");
if( val instanceof Double )
System.out.println("it is a Double");
}
public static void main(String[] args) {
int val1 = 3;
double val2 = 2.7;
checkNumber( val1 );
checkNumber( val2 );
}
}
The outcome of the previous example is:
it is an Integer
it is a Double
Process finished with exit code 0
Exercise 1: Creating the WordTool Class
WordTool is a class that will help you to perform a series of operations on a piece of text, including counting the number of words, looking at the frequency of letters, and searching for the occurrence of a specific string:
- Open IntelliJ and click on the File | New | Project menu options:
Figure 3.1: Creating a new project
- A new interface unfolds. The default options are meant for creating a Java program. You just need to click Next:
Figure 3.2: The New Project dialog box
- Check the box to create the project from a template. Select the template for the Command Line App. Click Next:

Figure 3.3: Creating a project from template
Name the project WordTool. Click Finish:

Figure 3.4: Adding the Project name
- By default, the template calls your basic class Main. Let's change that to WordTool. First, navigate within the new project to the Main.java file; it is displayed as the main entry in the list:
Figure 3.5: A template Java program
- Right-click on the Main entry and, in the drop-down list, select the Refactor option. Within that, select Rename…:
Figure 3.6: Refactoring the Java class
- A dialog window pops up. Write in it the name of the class, WordTool. The checkboxes allow you to choose which parts of the code will be refactored to fit the new name of the class:
Figure 3.7: Renaming the class in IntelliJ
- You will see that the class is now called WordTool and the file is WordTool.java:
Figure 3.8: WordTool
- Create the constructor for the class; it will be empty, in this case:
WordTool() {};
- Add a method to count the number of words in a string:
public int wordCount ( String s ) {
int count = 0; // variable to count words
// if the entry is empty or is null, count is zero
// therefore we evaluate it only otherwise
if ( !(s == null || s.isEmpty()) ) {
// use the split method from the String class to
// separate the words having the whitespace as separator
String[] w = s.split("\\s+");
count = w.length;
}
return count;
}
- Add a method to count the number of letters in a string, and add the ability to count both with and without whitespace characters:
public int symbolCount ( String s, boolean withSpaces ) {
int count = 0; // variable to count symbols
// if the entry is empty or is null, count is zero
// therefore we evaluate it only otherwise
if ( !(s == null || s.isEmpty()) ) {
if (withSpaces) {
// with whitespaces return the full length
count = s.length();
} else {
// without whitespaces, eliminate whitespaces
// and get the length on the fly
count = s.replace(" ", "").length();
}
}
return count;
}
- In the main class, create an object of the WordTool class and add a String variable containing some text of your choice:
WordTool wt = new WordTool();
String text = "The river carried the memories from her childhood.";
- Add code inside the main method to print out the calculations made by WordTool:
System.out.println( "Analyzing the text: \n" + text );
System.out.println( "Total words: " + wt.wordCount(text) );
System.out.println( "Total symbols (w. spaces): " + wt.symbolCount(text, true) );
System.out.println( "Total symbols (wo. spaces): " + wt.symbolCount(text, false) );
- Run the program; the outcome should be as follows:
Analyzing the text:
The river carried the memories from her childhood.
Total words: 8
Total symbols (w. spaces): 50
Total symbols (wo. spaces): 43
Process finished with exit code 0
Note
You can use the trick presented in this exercise to create classes for all the examples in this book, just by using the template and refactoring them to have the example name. After that, you will just need to copy the code in a fresh project.
Activity 1: Adding the Frequency-of-Symbol Calculation to WordTool
Add a method to the previously created WordTool class to calculate the frequency of a certain symbol. To do so, perform the following steps:
- Add a method to count the number of words in a string.
- Add a method to count the number of letters in a string, and add the possibility of separating the case of having whitespaces or not.
- In the main class, create an object of the WordTool class and add a string variable containing a line of text of your choice.
- Add code inside the main method to print out the calculations made by WordTool.
The expected outcome of this activity is as follows:
Analyzing the text:
The river carried the memories from her childhood.
Total words: 8
Total symbols (w. spaces): 50
Total symbols (wo. spaces): 43
Total amount of e: 7
Process finished with exit code 0
Note
The solution for this activity can be found on page 534.
- Web應用系統開發實踐(C#)
- Django+Vue.js商城項目實戰
- Web前端開發技術:HTML、CSS、JavaScript(第3版)
- GeoServer Cookbook
- 大學計算機基礎實驗教程
- 跟小海龜學Python
- Mastering LibGDX Game Development
- Visual C++數字圖像處理技術詳解
- 信息技術應用基礎
- INSTANT Django 1.5 Application Development Starter
- C語言程序設計學習指導與習題解答
- Go語言精進之路:從新手到高手的編程思想、方法和技巧(1)
- Multithreading in C# 5.0 Cookbook
- Domain-Driven Design in PHP
- Android應用開發深入學習實錄