1 / 21

Introduction to Development

Introduction to Development. Creating your first application. Learning Objectives. The basics of working with Console Apps Working with variables Basics of error handling Using classes and objects Calling functions and methods A high-level view of some OO concepts. Console Apps.

speier
Download Presentation

Introduction to Development

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Introduction to Development Creating your first application.

  2. Learning Objectives • The basics of working with Console Apps • Working with variables • Basics of error handling • Using classes and objects • Calling functions and methods • A high-level view of some OO concepts

  3. Console Apps • Also known as a Command Line App. A Console app is typically a small program designed to be executed from a command line (Windows Command Prompt). • Console Apps are really handy for developers as it allows us to try things and see the results very quickly – without worrying about UIs etc. • Console Apps can also be created very quickly in IntelliJ using the Console App Template. • This option is available when creating a new project – File – New Project and one of the setup options will be to create a Console App from the template.

  4. Console Apps The Console App template will contain the following code: The main method is what we call a Constructor. More on Constructors later but in this instance it’s essentially the first piece of code run in the Console App. The main method takes in a parameter called args which is an array of Strings (String[]). So if someone executed our app with the following: ConsoleApp.exe Rob Gillies 22 The first item in the array would be Rob, second Gillies and third 22 – all would be Strings. public class Main {public static void main(String[] args) { }}

  5. Console Apps Once the app is built you can run it from Windows Command line by browsing to the folder containing the .exe (executable file) and running it on the command line. Alternatively, while building the app it’s quicker to run it directly in IntelliJ by simply hitting the Play button or the various items in the Run menu. If you want to run it from within IntelliJ the parameters can be input in (Run – Edit Configurations – Program Arguments). In the image on the right I’ve created 3 test parameters Rob, Gillies, 30.

  6. Scenario JAM Computing is now a multinational company with 100s of employees. Every month I receive lots of payroll queries. As such, I want to build a system that handles these queries. I’m unsure how frequently this will be used so initially want a simple Console App that provides basic functionality – this will help us assess demand. As such I want to build a system that: • Allows an employee to search using staff number (integer) and surname and return a salary • Returns their pre-tax monthly income • Returns their post-tax monthly income – assume UK tax bands • If the employee inputs a third parameter (Country) and the value = US then use US tax bands

  7. GitHub Throughout the course will be using GitHub to share and store our code. I’ve built a small Console App and have added some classes that provide functionality that will help with this part of the course. Please Clone/Download the starting solution from the following URL: • https://github.com/jandmcomputing/IntroductionToCoding • See the link below for instructions on how to download (Clone) the solution: • https://www.jandmcomputing.com/using-githubfor GitHub help).

  8. Requirement 1 When tackling any build always try and tackle 1 requirement at a time, try to meet this particular requirement without too much consideration of everything else that is needed. This focus helps us break up large problems into smaller manageable chunks – this very much first into an Agile way of thinking. So the first req. we’re going to tackle is: • Allows an employee to search using staff number (integer) and surname and return a salary So for our Console App, we can now expect the incoming args array to contain staff number in the first position and a surname in the second i.e. args[0] = staff number and args[1] = surname.

  9. Creating a variable Requirement: Allows an employee to search using staff number (integer) and surname and return a salary So step one, we want two variables from our incoming args in our Console App: • Staff Number of type Int • Surname of type String Creating a variable will normally look like: modifier dataType name = value; For example: Public String Name = “Rob”; Where the modifier (scope) and assignment are optionable. Class Task – put arg[0] into a Staff Number variable and arg[1] into Surname.

  10. Creating a variable Class Task Answer – put arg[0] into a Staff Number variable and arg[1] into Surname. We earlier discussed how args was an array of Strings. So to assign args[0] to a Integer we have to convert or parse it. Notice how when hovering over these lines IntelliJ shows a yellow light bulb. This is IntelliJ keeping us honest and suggesting code improvements. In this case it’ll suggest you split the declaration and assignment onto two lines: String surname; Surname = args[1]; In this particular example, I do not agree with IntelliJ – one line is fine if we know the value at the time of declaration (in my opinion). intstaffNumber = Integer.parseInt(args[0]);String surname = args[1];

  11. Error Handling • What happens if there are less than 2 parameters? • What happens if the first argument contains a string and cannot be converted to an int? • Currently, both the above scenarios will cause our code to fail and a horrible error message/exception to be returned to the user. To stop this form happening we want to try and catch these type of exceptions and handle them elegantly. • Error handling can become a huge subject but for the sake of this requirement – we’ll try to stick to the following principle: • Solve for the error using IF (if possible) • For exceptional circumstances catch an exception (try…catch) • Class Task – add error handling for the two scenarios listed above.

  12. Error Handling Class Task Answer– add error handling around the above lines to catch the 2 errors described above. Notice how I’ve moved the Declaration of the variables outside of the try….catch. What happens if they’re declared inside the try….catch? intstaffNumber = 0;String surname = null;if (args.length< 2) {try{staffNumber = Integer.parseInt(args[0]);surname = args[1];}catch (Exception e) {System.out.println("Incorrect staff number inputted");System.exit(0);}} else {System.out.println("Invalid number of parameters inputted");System.exit(0);}

  13. Using a Class • Requirement - Allows an employee to search using staff number (int) and surname and return a salary Now we have the staff number and surname we want to get and return their salary. To help with this I’ve provided an Employee class that does all sorts of useful stuff – such as allow us to search using a staff number and surname and get back the salary. • A Class is a framework that describe the data and functionality of a collection of objects. So, Employee is our class and all of the Employees who work for us are the objects. This is an early look at some Object-orientated coding. This will be covered in a lot more detail later in the course – for now we’ll just be making use of the functionality provided by this class. Class Task - Have a look through the Employee task – how do you understand this to be working?

  14. Employee Class Example A class is made up of: • Attributes – the list of attributes in the class. Here we also state the scope(public/private) and data type of the attributes. • Constructor – this is the code called whenever the class is instantiated into an object. This can be completely blank which will create a blank object. Alternatively, the constructor can take in a set of variables used to build the object. • Accessors (or getters/setters) – these are simple methods and functions used to provide access to the outside world to the Attributes. We could have a nice big discussion about Encapsulation here but will save that for later in the course. • Methods – these may be private or public and offer functionality for manipulating or using the data within the class.

  15. Employee – Attributes private intstaffNumber;private String surname; Employee currently has 2 Attributes, staffNumber and surname. Notice all attributes are Private – this means they can only be accessed within the class. So from our Main class we cannot write or read to either of these variables. This is a nice and simple example of Encapsulation. Encapsulation is essentially wrapping everything related to the class/object within that class and strictly controlling access to this data/functionality to the outside world. For further reading Have a look at the numerous bank account examples on the Internet to explain the benefits of Encapsulation.

  16. Employee – Constructor public Employee(inteStaffNumber, String eSurname) {staffNumber= eStaffNumber;surname = eSurname;} The next piece of code to include is a Constructor. The Constructor is the piece of code called when you new-up a class. Every class needs at least 1 Constructor and it should always be named the same as the class (Address in this example). You can have multiple Constructors – have a quick Google for Overloading. In this example, the Constructor is taking in 2 parameters and assigning these to the local attributes. This is a common pattern when we have the data when instantiating a class. Once a Constructor is called, the object is created in memory and will remain available to you until it’s disposal.

  17. Employee – Methods/Functions public double getSalary() {if (validEmployee() == true ) { Random rand = new Random(); double salary = Math.random() * 10000; return salary;}else return -1;} Your class may contain any number of methods or functions that performs tasks related to the class. In our Employee class we have a function, getSalary that returns the employees salary. In this example we do not yet have a database of employee data so I’m simply returning a random number. Notice how we’re calling validEmployee, we’re using this to check if the employee exists. If validEmployee, which is another function within our class returns False then this method will return a -1 – telling the user of the class that the employee is invalid.

  18. Instantiating a Class Instantiating is the posh word for creating an Object. To create an Object we have to call the Constructor of a class. The usual syntax for this would be: classNameobjectName = new className(parameters for constructor); Running this will give you an instance of the class with the name objectName. So lets create an instance of our Employee class using the staffNumber and surname variables setup earlier: Employee emp = new Employee(staffNumber, surname);

  19. Working with Objects Now we have an instance of the Employee class called emp we can call getSalary to get the figure we want to return. To utilise a function within the class we can: • datatype variableName = objectName.functionName(any parameters needed by the function) • Class Task – using our new emp object get the salary from the getSalary function and return this to the user. Remember to handle the scenario when a -1 is returned for the salary. • Here’s an example of writing to the command line to help: System.out.println("Not a valid employee");

  20. Working with Objects Class Task Answer – using our new emp object get the salary from the getSalary function and return this to the user. Remember to handle the scenario when a -1 is returned for the salary. Employee emp = new Employee(staffNumber, surname);double salary = emp.getSalary();if (salary > 0) {System.out.println("Salary is: " + salary);} else {System.out.println("Not a valid employee");}

  21. Rest of the lesson • The rest of this less on would focus on completing the following 3 requirements: • Returns their pre-tax monthly income • Returns their post-tax monthly income – assume UK tax bands • If the employee inputs a third parameter (Country) and the value = US then use US tax bands A lot of the work would be an extension of the content already covered i.e. variables, error handling, calling functions and methods and some basic OO stuff. The final requirement would bring in some more complex objects and some looping. Have a look at the InternationalTaxBand class. You’ll understand be working with this with confidence by the end of this part of the course.

More Related