Java Programming Assignment

  • Note 1: Only use Java classes that are part of the standard Java SE SDK distribution! For the purpose of this assignment, you are not allowed to use any third party classes.
    Note 2: You will find plenty of “solutions” on the WWW that, at first glance, claim to do what this assignment asks you to do. Trust me, I have looked at them and they do not work correctly with respect to the details that our assignment asks you to implement, so please do yourself a favour and follow the instructions in this document and do your own work. This assignment is designed in such a way that a cut & paste job from the WWW will not work.
    All cases of plagiarism will be pursued! If in doubt, consult the Student Academic Integrity Policy or ask your lecturer.
    Java Programming Assignment
    The context for this assignment (all parts) is a ‘Days Alive Calculator’ - a small desktop application for calculating the number of days someone has been alive based on the date of birth and a second date, which may be today’s date or some other date. The program will allow the user to input the date of birth and a second date, then calculate and display the number of days a person has been alive.
    This assignment will test your knowledge of and skills in writing application software for a particular task, understanding the business rules of a particular problem, coding these in a computer program, developing a graphical user interface, connecting to a file on disk and connecting to an SQL database from within the program. As such, the assignment requires you to integrate and synthesise what you have learnt so far, in order to design and create a correctly working solution.
    For this assignment, you will use the Java programming language and development will be on the Eclipse IDE platform as practised in the computer lab classes. This assignment consists of several stages, with different requirements for undergraduate students in 4478 Introduction to IT and for graduate / postgraduate students in 8936 Introduction to IT G.
    ?? Stage 1: A simple console program (no GUI)
    ?? Stage 2: The same but wrapped in a GUI
    ?? Stage 3: Input comes from a text file – read only once, then information stored in a suitable data class, array, etc.
    ?? Stage 4: Input comes from an SQL database file.
    4478 IIT 8936 IIT G
    Part A – Stage 1 Part A – Stages 1 and 2
    Part B – Stage 2 Part B – Stage 3
    Part C – Stage 3 Part C – Stage 4
    Bonus – Stage 4
    Stage 4 is a bonus stage for undergraduate students to give you a stretch target. It allows you to pick up extra marks to make up for marks lost elsewhere in the assignment, but note that you cannot achieve more than 50/50 marks.
    Rules for Calculating the Number of Days Alive
    In simple terms, it is the difference between the date of birth and a second date, such as the today’s date. However, we must take into account that the months have a different number of days. In a non-leap year, these are:
    Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
    31 28 31 30 31 30 31 31 30 31 30 31
    However, in a leap year, the month of February will have 29 days.
    Leap years occur when:

  • images-19-1-24
    a. The year is evenly divisible by 4 (for example, 1996, 2004, 2008 etc.).
    b. If the year can be evenly divided by 100, then it is not a leap year (for example, the year 1900 was not a leap year).
    c. Unless it is also evenly divisible by 400, in which case it is a leap year (for example, the year 2000 was a leap year).
    We are not concerned here with the time of birth, so for the purpose of this assignment, both the day that a person was born and day of the second date count fully towards the total number of days. Test Cases
    When designing and implementing software applications, it is always important to first work out how to test the program(s) and what data to use, then to code. The following test cases have been designed to systematically test different conditions in the above rules. Use these to test your program, but make sure that your program can also handle other dates.
    Test Description Date of Birth Second Date #Days Alive
    No leap year 7 Jan 2013 18 Mar 2015 801
    Simple leap year 23 Aug 2009 1 May 2014 1713
    Leap years inclusive of the year 2000 9 Dec 1977 15 Jul 2012 12638
    Leap years inclusive of the years 1900 and 2000 30 Jun 1898 11 Nov 2010 41042
    Add all Java files (ending in .java) to a ZIP file. You do not need to zip the entire project folder, just the Java source file(s) (the ‘src’ folder). Submit the ZIP file via Moodle. There is no need for a cover sheet. By electronically submitting your assignment on Moodle, you acknowledge that this submission is your own work.
    Stage 1
    You are to write a software application using the Java programming language that enables a user to calculate the number of days a person has been alive from the date of birth until a second date, which may be the current date or a user determined date. In Stage 1, you will be developing a Java program without a GUI. Input and output are via the console.
    Step by Step Guide for Stage 1
    1. Think about your strategy first of how you will compute the total number of days alive based on the above rules. Different strategies are possible. Here is one:
    a. Use an integer array of 12 elements to hold how many days each month has.
    b. For the birth year, from the date of birth (inclusive), count the number of days left in that year.
    c. For all years between the birth year and the year of the second date (but not inclusive of the latter year), add 365 days to the total per year.
    d. For each of these ‘in-between years’, add an extra day if it is a leap year.
    e. For the year of the second date, count the number of days up to and inclusive of the second date and add to the total.
    f. The total is then the number of days a person has been alive on the day of the second date.
    2. Create a new Java project.
    3. Add a simple Java class named Stage1. Do not add a GUI.
    4. In the Stage1 class (file, you may put all code for the user interaction and the calculation into the main method. (You might still need to define global variables and constants outside the main method at the start of the class.)
    5. In the main method, add code to read in the day, month and year information from the console. In Java, there are different ways to do this. One of the recommended ways is to use the Scanner class:
    Scanner inConsole = new Scanner (;
    // Read the Day information for the Date of Birth
    System.out.print(“Enter the Day of the Date of Birth: ”); int iDayBirth = inConsole.nextInt();
    Repeat (and adapt) the last two lines for the other five pieces of information (month and year for date of birth, and day, month and year for the second date).
    6. Now add the code that implements your strategy of calculating the number of days alive based on your strategy developed under 1.
    7. Finally, add a System.out.println() statement that states the result on the console.
    8. Test your implementation with the test cases mentioned above (and additionally your own).
    What the tutors will be looking for
    The tutor’s instructions include
    • Constants vs literals. Using constants is important for the ease of maintenance. Not using constants will result in lower marks. For example, consider constants for the default number of days in a non-leap year (365) and leap year (366).
    • Program code layout. Separate blocks of code by a blank line. Use comments.
    • A comment is not an essay. Comments are important for the maintenance of your program and should contain enough details, but keep them concise. Do not comment every single line.
    • The program must have a prologue. Check style against the Java style guide attached below (last 4 pages).
    • Good names for your variables and constants. Check style against the Java style guide attached below (last 4 pages).
    • Does the program work correctly? Are the elements drawn the right way?
    Please refer to the Java Assignment Marking Feedback sheet for details on marks, as these differ for 4478 IIT and 8936 IIT G students.
    Stage 2
    As the user input and program output via the console is not very satisfactory from an humancomputer interaction and usability point of view, your task here is to design and implement a Java Swing GUI application that provides an easy to use interface.
    Your task in Stage 2 is to develop a GUI (using the built-in WindowBuilder in Eclipse and Java Swing components) that allows a user to input the data of the date of birth and a second date. To this end, the user can
    • input the data using Java Swing GUI elements, e.g. text fields, radio buttons, drop down lists, etc.,
    • click on a Calculate button that starts the calculation of the number of days based on the current input and displays the output, and
    • an Exit or Quit button to properly close the program.
    Use the same code for the calculation of the number of days as in Stage 1. Reusing code is an important part of software development.
    You have a great degree of freedom in what GUI elements you choose and how you would like to design the layout of your GUI. The below example is really just that – an example the design, which you can copy if you are feeling uninspired to come up with your own design. What matters is the functionality of the design and that the user can input the required data in a sensible fashion.
    Example of what the “empty” GUI might look like.
    • For this assignment, you do not have to do any checking for invalid user input (you may of course, if you want to), for example you do not have to check whether the user has typed in a negative number or a letter in the text fields for day, month or year. Checking for invalid user input will be discussed in lectures later in the semester.
    • Your user interface does not have to be identical to the one above. This is just an example of how the GUI could look.
    • Your GUI should update the output label “Days Alive: …“ in an appropriate manner with the number of days when the Calculate button has been clicked.
    What the tutors will be looking for
    The tutor’s instructions include
    • Constants vs literals. Using constants is important for the ease of maintenance. Not using constants will result in lower marks. For example, in addition to Stage 1, consider constants for the default width and height of the text fields so as to easily achieve a uniform look.
    • GUI Design. Is it simple to use and easy to understand? Are all required components there?
    • Program code layout. Separate blocks of code by a blank line. Use comments.
    • A comment is not an essay. Comments are important for the maintenance of your program and should contain enough details, but keep them concise. Don’t comment every single line.
    • The program must have a prologue. Check style against the Java style guide attached below (pp. last 4 pages).
    • Good names for your variables and constants. Check style against the Java style guide attached below (last 4 pages).
    • Does the program work correctly? Are the elements drawn the right way?
    Please refer to the Java Assignment Marking Feedback sheet for details on marks, as these differ for 4478 IIT and 8936 IIT G students.
    Step by Step Guide for Stage 2
    1. Draw a sketch of your graphical user interface on paper. What Java Swing components will you use? Where will you place them? The above GUI is just an example. You can copy the design of it or create your own.
    2. Add to the same project that was used for Stage 1, a new Application Window class (New ? Other ? WindowBuilder ? Swing Designer ? Application Window) for your GUI.
    3. As in the lectures, workshops and lab classes, give that Java application a suitable name (and optionally package name) of your choice.
    A new JFrame object will be created and you should be able to switch between the Java source code for it as well as the empty GUI in the WindowBuilder editor in Eclipse.
    4. Right-click on the grey area inside the JFrame and set the layout to “Absolute layout”. (Note, this shows up as “null” layout in the source code.)
    5. Adjust the size of the JFrame to a suitable size for your GUI.
    6. Add all the components for your GUI. Use Java Swing components, which you can add via the Palette in the WindowBuilder’s Design view. Make sure that the names you use for these components comply with our Java Style Guide (see below).
    7. Add event handlers (ActionListeners) for your buttons, radio buttons, check boxes, etc. To do so, in the GUI editor right-click on the element (say, a JButton) and select Add event handler ? action ? actionPerformed. (Similar events may be needed for your checkboxes, radio buttons, etc.)
    8. Add the code that does the actions, e.g. that does the calculation of the number of days.
    9. Reuse your code for the calculation of the number of days from Stage 1 by copying and pasting it from the Stage 1 main method into the Calculate button’s event handler.
    10. Test your application! Run it as a Java Application. Enter the test cases listed above and check if your program gives the same result.
    11. Make sure your code adheres to the Java style guide. Check for prologue comment and other comments in your code. You need to manually add more comments than the automatically generated comments!
    Stage 3
    In Stage 3 of the assignment, the input will not come directly from the user any more, but rather from a text file.
    The file dates.txt contains the details of people. Each line of this file contains the details of exactly one person. Each person is listed by name, data of birth, and second date. These are separated by semicolons, while the day, month and year information in the dates is separated by commas.
    Here is an example:
    Walter Krohn;2,12,1891;15,3,2015
    You will need to copy dates.txt into the same directory of your Eclipse project that holds the .project file. (Do not copy the file into the src or bin folders.)
    Your task will be to add code to your program that reads all person data from the text file, puts these into appropriate storage in memory (I suggest you create a data class similar to the example in and then create an array or vector that will hold each instantiation of that data class), and updates the “Days Alive: …” label output after calculation.
    For testing, the details of the file may change, but the structure will not.
    • For this part of the Java assignment, add Java Swing GUI components that allow the user to select a person’s name, via a JList, and that calculate the number of days alive as well as draws a bar graph like comparison of the number of days between all persons mentioned in the text file.
    • The bar graph should be drawn as soon as a person’s name is selected in the JList.
    • Update the label “Days Alive: …” according to the information for the currently selected person by getting the relevant information from the storage in memory and calculating the number of days..
    • Add two radio buttons to the program, so that the user can select whether s/he wants to use the second date from the file or want to use their own. In turn, this means that you must add data entry text fields as well.
    • Try to reuse code, such as the code for the drawing, from Part A. This will mean that you should have the GUI code separated from the drawing code and the file reading code (i.e. in a separate method or separate methods). This is good programming style!
    • Remember that it is good practice to have a Quit button in your GUI to exit the program.
    What the tutors will be looking for
    The tutor’s instructions include (apart from the usual such as good variable names, prologue / comments, code layout, …)
    • Use of constants. Think about where you could use constants here. Same as in Stage 1 and 2.
    • The text file should only be read once. You probably want to do that at the start of the program. Consider how you would do that.
    • Correct calculation of the number of days and display of bar graph comparison based on the details in the file.
    • Separate GUI functionality from drawing. Students should use a separate method for the drawing. It is good practice and follows good programming style to separate GUI code from other code.
    • There are various ways you can store the data when reading the file. You could use a multidimensional array, or create your own data class and then use an array or vector of this new data type. Using your own data class is preferential.
    Stage 4
    Here, the input will now come from a MS Access database contained in the file dates.mdb. This file is available on the IIT / IIT G web site on Moodle (UC LearnOnline).
    There are one table in the database, tblDates.
    The table tblDates contains fields “name”, “dayDOB”, “monthDOB”, “yearDOB”, “dayCurrent”, “monthCurrent”, and “yearCurrent”.
    A typical record would be Walter Krohn, 2, 12, 1891, 15, 3, 2015 .
    Write a Java program with a GUI (Note: extending your GUI program from Stage 3 is acceptable, but you could also write a separate Java file for Stage 4; either way is OK) that allows the user to do the following:
    • Let the user select the name of a person from a list (e.g. JList) and display the bar graph comparison of the number of days the selected person has been alive in comparison to the other persons. Highlight the currently selected person’s bar graph in a different colour. Update the labels in the GUI showing the date of birth, second date and “Days Alive: …”.
    • Create a database report consisting of all persons, including all fields from tblDates plus a column that shows the number of days each person has been alive for. The report should be in ascending alphabetical order of “name”. It should be written to a text file
    “database_report.txt”. Make sure that your columns are properly aligned. Text columns should be left aligned, number columns right aligned.
    • You may extend your GUI from Stage 3 to include Stage 4, in fact you could start from Stage 2. If you do, label the parts clearly with “Stage 2”, “Stage 3”, and “Stage 4”, so that your tutors know which part of your program is in reply to what part of the assignment. Alternatively, you may write a separate file for each stage but can reuse code.
    • Use a Disconnected Database Access model, i.e. connect to the database, run the SQL command, get the resulting virtual table in the ResultSet object, then disconnect again. Do not connect to the database and download / store all database information in local storage.
    In this part of the assignment, you will write a number of database reports. Each report should
    • include a header,
    • include a column header,
    • have columns lined up, with text columns left justified and numeric columns right justified.
    • make provision for multi-page reports. At least one of your reports should actually be more than one (fictional) page in length. Do this by defining the report page length as 5.
    All reports should be written to a text file (rather than a real printer). You do not need to submit a hardcopy of the report.
    What the tutors will be looking for
    The tutor’s instructions include (apart from the usual such as good variable names, prologue / comments, code layout, …)
    • Make sure that the lines in the database reports are split into pages and the columns are lined up and correctly formatted.
    • Correct connection to the database.
    • Correct calculation of the number of days based on the input from the database file.
    • Correct display of the bar graph comparison in the drawing area.
    Java Style Guide
    Your programs should be
    • Simple
    • Easy to read and understand
    • Well structured
    • Easy to maintain
    Simple programs are just that. Avoid convoluted logic, nested if-statements and loops, duplicating execution (such as reading files multiple times), repeated code, being “clever”.
    Programs can be made easier to read by following the “Layout” and “Comments” guidelines below.
    Well structured code uses methods and functions to help tame complexity.
    If programs are simple, easy to understand and well structured they will be easy to maintain. Easily maintained programs will also use constants rather than literals, and use built-in functions and types. Layout
    The text editor in the Eclipse IDE does a good job of automatically laying out your program. You can control this operation to some extent (using the Tools/Options menu). However, you are unlikely to need to do so.
    White space
    Use white space freely:
    • A blank line after declarations
    • 2 blank lines before each function declaration
    • A bank line between sections of a program or after a sequence of statements to separate a block of statements.
    Well chosen names are one of the most important ways of making programs readable. The name chosen should describe the purpose of the identifier. It should be neither too short nor too long. As a guide, you should rarely need to concatenate more than 3 words.
    Letter case
    Constants use ALL_CAPITALS. e.g. PI, MAXSTARS
    Variables use firstWordLowerCaseWithInternalWordsCapitalised e.g. cost, numStars
    It is a good idea to use the so called Hungarian notation where the first letter (or two) indicate what type the variable has:
    • i for int, e.g. iNum
    • l for long, e.g. lNum
    • c for char, e.g. cLetter
    • b for byte, e.g. bNum
    • f for float, e.g. fFloatingPointNum
    • d for double, e.g. dFloatingPointNum
    • s for String, e.g. sName
    • bo for Boolean, e.g. boCar
    Methods (subs and functions) use firstWordLowerCaseWithInternalWordsCapitalised e.g. cost(), numStars()
    Recall that the IDE preserves the capitalisation of the declarations.
    Types of names
    1. Names of controls / GUI elements should have a prefix indicating the type of control (Java Swing). The prefix should be lower case with the remainder of the name starting with upper case.
    Control prefix example
    text box label list box
    combo box command button radio button check box panel track bar / slider jTextArea jLabel jList jComboBox jButton jRadioButton jCheckBox jPanel jSlider jTextArea_Amount jLabel_Result jList_Students jComboBox_Shares jButton_Quit jRadioButton_Colour jCheckBox_Salt jPanel_Drawing jSlider_X
    2. Names of functions should be nouns or noun-phrases
    newSum = sum(alpha, beta, gamma)
    newSum = sumOfStudents(alpha, beta, gamma)
    rather than
    newSum = computeSum(alpha, beta, gamma)
    3. Names of methods should be imperative verbs
    printResults(newSum, alpha, beta)
    rather than
    results(newSum, alpha, beta, gamma)
    4. Names of Boolean functions should be adjectives or adjectival phrases
    if (empty(list))
    if (isEmpty(list))
    rather than
    if (checkIfEmpty(list))
    Comments should explain as clearly as possible what is happening. They should summarise what the code does rather than translate line by line. Do not over-comment.
    In Java, you can either use /* Comment */ for a block comment possibly extending over multiple lines, or you can use // Comment for a one-line comment.
    Comments are used in three different ways in a program:
    • Heading comments
    • Block comments
    • End-of-line comments.
    Heading comments: These are generally used as a prologue at the beginning of each program, procedure and function. They act as an introduction, and also describe any assumptions and limitations. They should show the names of any files, give a short description of the purpose of the program, and must include information about the author and dates written / modified.
    Block comments: In general, you should not need to comment blocks of code. When necessary, these are used to describe a small section of following code. They should be indented with the program structure to which they refer. In this way the program structure will not be lost.
    End-of-line comments: These need to be quite short. They are generally used with parameters to functions (to explain the purpose and mode of the parameter), and / or with variable declarations (to explain the purpose of the variable), and are not meant to be used for code. In Java, use // for endof-line comments.
    Comment data, not code: Comments about the data – what it is and how it is structured - are much more valuable than comments about the code.
    Each of your programs should have a prologue. This is a set of “header comments” at the top of
    Form 1. It should include
    who wrote it // Author: Roland Goecke
    when it was written // Date created: 12 Feb 2013
    when it was last changed // Date last changed: 1 Mar 2013
    what it does // This program does...
    what files it reads / writes // Input: sample.txt, Output: none
    A literal is a number such as 10 that is stored in a variable. You should avoid literals in your program code. Instead use constants. They are stored differently in the computer memory and can be used more efficiently by the compiler / interpreter. For example, instead of int fine = 80;
    public static final int SPEEDING_FINE = 80;
    fine = SPEEDING_FINE;
    This makes your program easier to maintain. If the speeding fine changes, the change only has to be made in the one place.
    Methods and Functions
    Using methods and functions is one of the simplest and most effective ways of dealing with complexity in a program.
    When you write your own method or function to perform a calculation, it should not refer to any GUI controls. Do not mix IO and calculations in a method or function.
    • encapsulates a task
    • name should be a verb. Example: printReport()
    • should only do 1 task.
    o encapsulates a query
    o return type is int, boolean, double…;
    o if return type is boolean, name should be an adjective, otherwise name should be a noun.
    ?? Examples: isEmpty(list), SquareRoot(number) o should answer only 1 query.
    Comments for each function and method (to be placed on the line before the method / function starts)
    name above rules apply
    purpose what it evaluates or what it does
    assumptions any assumptions made, particularly on the arguments
    Duplicated Code
    View any duplicated code with suspicion. Look for a way of factoring the duplicated code into a method.
    Built-­-in functions
    Unless you have a good reason, use built-in functions rather than writing (or not writing) your own. They will be correct, flexible and familiar to a reader.
    Using types is an important way of making your intentions clear. Java does not allow you to be
    sloppy with your types. In IIT / IIT G, you are expected to choose appropriate types. You are also expected to use type conversions such as Integer.parseInt(“123”) and Double.toString(123.45).
    Simplicity has long been recognised as one of the most important characteristics of programming. There are many ways of simplifying programs. These include avoiding nested IF statements, nested loops and complex conditions.