Start learning with our library of video tutorials taught by experts. Get started

Java Essential Training

Creating a more complex calculator application


From:

Java Essential Training

with David Gassner

Video: Creating a more complex calculator application

If you've been following along through the entire course, you've just learned how to build your own methods, how to encapsulate functionality inside methods that are parts of classes. I'm going to use these tools to expand on the example of the calculator application that I showed you how to build in an earlier chapter. I've opened up a version of the calculator that currently only adds data together. It accepts two values from the command line through two calls to the getInput method, converts those values to double values, and then adds them together. We're going to add functionality to the calculator now, so that it can not only add but can also subtract, multiply and divide.
Expand all | Collapse all
  1. 10m 8s
    1. Welcome
      1m 3s
    2. Is this course for you?
      5m 35s
    3. Using the exercise files
      3m 30s
  2. 31m 24s
    1. The history of Java
      5m 19s
    2. Java compilation and syntax
      8m 54s
    3. Understanding the principles of Java
      8m 28s
    4. Choosing a development environment
      8m 43s
  3. 19m 5s
    1. Installing Java on Windows
      6m 42s
    2. Installing Eclipse on Windows
      3m 19s
    3. Exploring Java on Mac OS X Leopard and Snow Leopard
      2m 27s
    4. Installing Java on Mac OS X Lion
      3m 27s
    5. Installing Eclipse on Mac OS X
      3m 10s
  4. 46m 10s
    1. Creating a Hello World application
      11m 7s
    2. Exploring the Eclipse IDE
      8m 55s
    3. Compiling and running from the command line
      8m 2s
    4. Passing arguments to the application
      8m 17s
    5. Using the Java API documentation
      4m 5s
    6. Memory management and garbage collection
      5m 44s
  5. 58m 57s
    1. Everything is an object
      5m 59s
    2. Declaring and initializing variables
      9m 15s
    3. Working with numbers
      8m 32s
    4. Converting numeric values
      6m 40s
    5. Understanding operators
      7m 58s
    6. Working with character values
      5m 14s
    7. Working with boolean values
      5m 13s
    8. Outputting primitive values as strings
      5m 33s
    9. Creating a simple calculator application
      4m 33s
  6. 53m 40s
    1. Writing conditional code
      5m 35s
    2. Using the switch statement
      8m 50s
    3. Repeating code blocks with loops
      7m 35s
    4. Creating reusable code with methods
      6m 31s
    5. Declaring methods with arguments
      5m 41s
    6. Overloading method names with different signatures
      5m 53s
    7. Passing arguments by reference or by value
      5m 35s
    8. Creating a more complex calculator application
      8m 0s
  7. 20m 30s
    1. Using the String class
      5m 44s
    2. Building strings with StringBuilder
      3m 34s
    3. Parsing string values
      3m 19s
    4. Working with date values
      7m 53s
  8. 20m 44s
    1. Understanding compile-time vs. runtime errors
      4m 5s
    2. Handling exceptions with try/catch
      4m 55s
    3. Throwing exceptions in methods
      2m 50s
    4. Using the debugger
      8m 54s
  9. 32m 22s
    1. Using simple arrays
      4m 47s
    2. Using two-dimensional arrays
      6m 17s
    3. Managing resizable arrays with ArrayList
      7m 14s
    4. Managing unordered data with HashMap
      6m 5s
    5. Looping through collections with iterators
      7m 59s
  10. 52m 2s
    1. Understanding encapsulation
      5m 59s
    2. Creating and instantiating custom classes
      8m 8s
    3. Organizing classes with packages
      6m 47s
    4. Creating and using instance methods
      6m 52s
    5. Storing data in instance variables
      6m 56s
    6. Using constructor methods
      5m 40s
    7. Managing instance data with getter and setter methods
      8m 26s
    8. Using class variables and Enum classes
      3m 14s
  11. 41m 15s
    1. Understanding inheritance and polymorphism
      9m 12s
    2. Extending custom classes
      9m 1s
    3. Overriding superclass methods
      3m 8s
    4. Casting subclass objects
      5m 3s
    5. Understanding interfaces and implementing classes
      4m 2s
    6. Creating your own interfaces
      4m 14s
    7. Using abstract classes and methods
      6m 35s
  12. 32m 17s
    1. Managing files with the core class library
      7m 46s
    2. Managing files with Apache Commons FileUtils
      7m 32s
    3. Reading a text file from a networked resource
      7m 52s
    4. Parsing an XML file with DOM
      9m 7s
  13. 17m 39s
    1. Creating your own JAR files
      4m 54s
    2. Understanding the classpath
      5m 2s
    3. Documenting code with Javadoc
      7m 43s
  14. 47s
    1. Goodbye
      47s

Watch this entire course now—plus get access to every course in the library. Each course includes high-quality videos taught by expert instructors.

Become a member
Please wait...
Java Essential Training
7h 17m Beginner Dec 14, 2011

Viewers: in countries Watching now:

Join author David Gassner as he explores Java SE (Standard Edition), the language used to build mobile apps for Android devices, enterprise server applications, and more. This course demonstrates how to install both Java and the Eclipse IDE and dives into the particulars of programming. The course also explains the fundamentals of Java, from creating simple variables, assigning values, and declaring methods to working with strings, arrays, and subclasses; reading and writing to text files; and implementing object oriented programming concepts.

Topics include:
  • Understanding the history and principles of Java
  • Installing Eclipse and Java
  • Compiling and running from the command line
  • Managing memory and performing garbage collection
  • Declaring and initializing variables
  • Writing conditional code
  • Building and parsing strings
  • Debugging and exception handling
  • Using simple arrays
  • Creating custom classes
  • Working with encapsulation, inheritance, and polymorphism
  • Managing files
  • Documenting code with Javadocs
Subjects:
Developer Programming Languages
Software:
Android Java Eclipse
Author:
David Gassner

Creating a more complex calculator application

If you've been following along through the entire course, you've just learned how to build your own methods, how to encapsulate functionality inside methods that are parts of classes. I'm going to use these tools to expand on the example of the calculator application that I showed you how to build in an earlier chapter. I've opened up a version of the calculator that currently only adds data together. It accepts two values from the command line through two calls to the getInput method, converts those values to double values, and then adds them together. We're going to add functionality to the calculator now, so that it can not only add but can also subtract, multiply and divide.

The first step is to convert these three lines of code into their own method. I'll select those three lines and right click, then go to Refactor, Extract Method. I'm asked for the new Method name and I'll call it addValues. I've selected this option, Declare thrown runtime exceptions. I'll described runtime exceptions in more detail later in the course. But for now what you need to know is that when you convert a value using a parsing function, if the value can't be converted, an exception will be thrown.

When an exception is thrown, you get an instance of a particular class, in this case a class named NumberFormatException. And it's good practice in Java to declare those exceptions, so that they can be easily handled later on in the code. I'll click OK and that result in extracting the code into the addValues method. I'll Save and Run the application to make sure it's still working the way I want to. I'll add together values of 5 and 10 and get 15, so all is good. Now it's time to ask the user what operation they want to do. Instead of just assuming they're going to add the values, we'll let them enter a numeric selector, one for addition, two for subtraction and so on.

I'll get another input value, I'll declare a variable named String and I'll name it op for operation. I'll call getInput and I'll set the prompt like this, Enter 1=Add, 2=Subtract, 3=Multiply, and 4=Divide. Now the code is getting little wide, so I'll double click to expand my editor and we can see all the code on that line now. The next step will be to convert that op value to an integer so that I can process it in a switch statement.

I'll declare an int named opInt for operation as an integer, and I'll convert it using this code, Integer.parseInt, I'll parse in op, and now I have an integer which indicates what the user wants to do. Now, I'm going to examine that integer value in a switch statement. I'll look for the values 1, 2, 3 and 4 and then execute the requested operation. I'll type in the word switch; I'll press Ctrl+Space and choose switch case statement. I'll set the key I'm examining to opInt and I'll set the first case statement value to 1.

Then I'll take this command, which is adding the values together, and I'll cut and paste it into the case statement. So I'm saying if the user chose 1, I'm adding the values together. Now I'm going to select the entire case statement, I'll copy those to the clipboard and I'll paste them in three times. I'm just going to add and subtract a little bit of white space, so this is a little easier to read. Now I'll take the three new cases and I'll change what they do. I'll change the values I'm looking for to 2, 3 and 4.

And I'll change the methods that I'm calling, so that instead of always calling addValues, I can also call subtractValues, multiplyValues and divideValues. I'll save my changes and show you that there are some errors showing up. I will move the cursor over the error marker and the one I'm looking for is the one that says Duplicate local variable result, this variable is being declared four times in the same code block, and that breaks the rule of Java. Each variable can be declared only once within a particular code block, a code block being delimited by the curly braces.

When you have this kind of situation, the solution is to move the declaration of the variable outside of the code block and then simply address the variable within the code block. So I'm going to take this code, double result, and I'll copy it to the clipboard, I'll move the cursor above the switch statement and paste it in, and I'll finish the declaration with the semicolon. Then I'll move down to the switch statement and I'll remove the data type declarations from each of the four cases, because the variable has already been declared at this point, now all I need to do is address the variable.

I'll save my changes and see that I still have some errors. The next error tells me that the subtractValues method is undefined and that's true. I've only created a method so far called addValues. Now I could go and explicitly type out a new method or I could let Eclipse do it for me. So to let Eclipse do the work, I'll move the cursor over one of the method names that's undefined and a little window pops-up and says, there's a quick fix available, do I want to create a method named subtractValues that accepts two string arguments? Well, that's exactly what I want to do.

So I'll click the link, and then I'll scroll down a bit and I'll see that Eclipse has generated that method for me. I'll go back up to the case statements and do the same thing for multiply values and divide values. You can see how much time Eclipse is saving me by generating the method signatures. I'm going to close-up this code a little bit, and then I'll move down to my new methods, divide, multiply and subtract. The code within the addValues method is almost the same as I want in all four of these methods, so I'm going to select it and copy it, and then I'll paste it into place for each of the other methods.

And all I need to do in each of these methods is change the operator. For subtract I'll use the dash for multiply, I'll paste in the code and change the operator to an asterisk, and for divide, I'll select that extra code, delete it paste in the other code and change the operator to a forward slash. I'm pretty close to being done, there's still one error there. The local variable result may not have been initialized, so I'll click the error and I'll get another set of quick fix proposals, one of them is the correct suggestion.

When you declare a variable that's outside a code block, but you're only going to set its value inside a code block, the Java compiler wants you to initialize its value when you declare it, so I'll go back up to the line where I declared result and I'll set it 0. Now finally I have one more bit of code to take care of. I've asked the user to type values of 1, 2, 3, or 4, but what if they type another value? I'll move the cursor after the default case, but before the break statement and in this case I'll tell the user you selected a value I didn't understand.

I use System.out.println, (" You entered an incorrect value"); and then to terminate the application at that point, I'll use the Return keyword. I no longer need the break statement there, because if we got into the default block that means the application is done. I'll go ahead and run the application let's see how we do. I'll type in two numeric values 10 and 5, and instead of adding, this time I'm going to divide, by typing in the number 4, and I get the value 2, and that's correct. I'll run the application again, once again, I'll type in 10 and 5 and this time I'll multiply it by typing 3, and I get 50.

So now my calculator is handling all four values. It's still possible to break the application, for example, what happens if I type values here, 5 and 10, but then instead of typing a numeric value I type a string value, I'll get an exception. I'll show you how to handle these exceptions and how to debug your application in a later chapter, but what's important to know at this point is that you now know how to accept values from the user, how to examine those values, how to process them conditionally, using if statements and switch statements, and how to execute simple math operations.

This application, file trivial, is using many important parts of the Java programming language. And you're now ready to move on to other aspects of the language that can give your applications even more power.

There are currently no FAQs about Java Essential Training.

Share a link to this course
Please wait... Please wait...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.
Upgrade now


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

Upgrade now

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed Java Essential Training.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Welcome to the redesigned course page.

We’ve moved some things around, and now you can



Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked