Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member
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.
Get unlimited access to all courses for just $25/month.Become a member
82 Video lessons · 98095 Viewers
61 Video lessons · 85367 Viewers
71 Video lessons · 69378 Viewers
56 Video lessons · 101735 Viewers
Access exercise files from a button right under the course name.
Search within course videos and transcripts, and jump right to the results.
Remove icons showing you already watched videos if you want to start over.
Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.
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.
Your file was successfully uploaded.