官术网_书友最值得收藏!

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:

  1. Open IntelliJ and click on the File | New | Project menu options:

    Figure 3.1: Creating a new project

  2. 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

  3. 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

  1. 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

  2. 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

  3. 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

  4. You will see that the class is now called WordTool and the file is WordTool.java:

    Figure 3.8: WordTool

  5. Create the constructor for the class; it will be empty, in this case:

    WordTool() {};

  6. 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;

        }

  7. 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;

        }

  8. 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.";

  9. 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) );

  10. 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:

  1. Add a method to count the number of words in a string.
  2. 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.
  3. In the main class, create an object of the WordTool class and add a string variable containing a line of text of your choice.
  4. 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.

主站蜘蛛池模板: 台北市| 镇雄县| 故城县| 钟山县| 奇台县| 四子王旗| 阳江市| 白水县| 清河县| 台州市| 和平县| 罗定市| 常宁市| 永登县| 泸水县| 桂阳县| 漳浦县| 哈密市| 绥江县| 贡嘎县| 景洪市| 茶陵县| 于都县| 邯郸县| 凤山县| 巴彦淖尔市| 太仆寺旗| 博湖县| 宁都县| 冷水江市| 鹿泉市| 炉霍县| 舞阳县| 体育| 苍溪县| 满城县| 岢岚县| 德安县| 惠州市| 惠来县| 杂多县|