联系方式

  • QQ:99515681
  • 邮箱:99515681@qq.com
  • 工作时间:8:00-21:00
  • 微信:codinghelp

您当前位置:首页 >> Java编程Java编程

日期:2018-10-17 10:16

Java Programming Assignment

Introduction to Information Technology/G 4478/8936

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 except for

UCanAccess1

if you attempt stage 4.

Note 2: Familiarise yourself with the Java Style Guide at the end of this document.

Note 3: All cases of plagiarism will be pursued! If in doubt, consult the Student Academic

Integrity Policy http://www.canberra.edu.au/current-students/canberra-students/conduct

The context for this assignment (all parts) is a ‘Fuel App’ for calculating and displaying fuel

consumption of a given vehicle. This assignment will test a student’s 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,

reading data from a text 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, students 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 four 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. Includes an advanced GUI

Stage 4: Input comes from an SQL database file. Generates a Database Report. Includes

the advanced GUI

4478 IIT 8936 IIT G

Part A – Stage 1 (25 marks) Part A – Stages 1 and 2 (27 marks)

Part B – Stage 2 (10 marks) Part B – Stage 3 (13 marks)

Part C – Stage 3 (15 marks) Part C – Stage 4 (10 marks)

Bonus* – Stage 4 (up to 10 marks)

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


1

http://ucanaccess.sourceforge.net/site.html

IIT/IIT G Java Assignment 2018 S2 r0

Fuel App

Preamble: A client has approached you with a request to write a software application to track

the fuel usage of their vehicle fleet. Following data are gathered for each filling;

a) Amount of fuel purchased (x litres) [float]

b) Price of fuel (y cents/litre) [integer]

c) No of kilometres the vehicle was driven on that filling (z km) [float]

The client requires the application to track the last five such fillings for any given vehicle and

alert if the average cost goes above 16 cents per km (inclusive of).

A Worked example: Let’s calculate the average fuel consumption for a single filling. Using

the notation above;

The average fuel consumption (afc_1) = x/z (litres per km)

The average cost (ac_1) = (x/z)*y (cents per km)

Then for five fillings;

The overall Average Fuel Consumption (afc) = {afc_1+ afc_2+…+ afc_5}/5

The overall Average Cost (ac) = {ac_1+ ac_2+…+ ac_5}/5

You’ll also need to check if ac exceeds client set threshold of 16 cents per km warning.

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 the two different conditions of average cost warning. You

may construct additional test cases. Please note that you’re not expected to check for the

validity of input data in your assignment. For example the program could crash if the user input

0 for z as it will result in a division by zero error. (Notation: fuel_n – no of litres of fuel

purchased; price_n – price of a litre of fuel in cents; km_n; distance travelled in km for the n

th

filling)

Test Description Vehicle fuel_1 price_1 km_1 fuel_2 price_2 km_2

The average costs goes above 16

cents

Holden 10.6 151 100.0 10.6 151 100.0

Average cost is below 16 cents Toyota 33.0 177 412.5 45.6 55 570.0

Table continued…

fuel_3 price_3 km_3 fuel_4 price_4 km_4 fuel_5 price_5 km_5 afc ac

10.6 151 100.0 10.6 151 100.0 10.6 151 100.0 0.1 16.0

51.6 104 430.0 25.0 50 277.8 12.4 91 124.0 0.1 8.9

IIT/IIT G Java Assignment 2018 S2 r0

Submission Instruction

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 Canvas (max. size 10MB).

Click the submit button to upload the zipped file and submit assignment.

Stage 1:

Write a simple Java program to calculate the average fuel consumption and the average cost for

a single filling. Then extend this to include five fillings and calculate the overall average fuel

consumption (afc) and average cost (ac) for the five fillings. You’ll also need to warn the user if

the average cost is equal to higher than 16cents. In Stage 1, you will be developing a Java

program without a GUI. Input and output are via the console.

When the program is executed, the user will be asked to input;

Amount of fuel purchased (in litres)

Price of ONE litre of fuel (in cents)

The distance travelled after the filling (in km)

for five consecutive fillings.

Then the program should display afc and ac for the data and indicate if the ac is below the

warning level.

Step-by-Step Guide for Stage 1

1. Think about your strategy for how you will calculate the afc_n and ac_n for each filling.

And then how you work out the overall afc and ac using these calculations. Think about

writing simple functions/methods for the repetitive calculations.

2. Create a new Java project. You may call it JavaAssignment.

3. Add a simple Java class named Stage1. Do not add a GUI.

IIT/IIT G Java Assignment 2018 S2 r0

4. In the Stage1 class (file Stage1.java), 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.) Declare

and instantiate the variables that you will need for Stage 1. You will also need several

integer arrays to hold the fuel amount, price, and distance travelled, at the start of the

main method, for example (you’ll need to add additional arrays):

float[] faFuelAmount = new float[5]; // Array to hold the fuel amounts

5. Add code to read in the data from the user for the five fillings. A recommended way is

to use the Scanner class (import java.util.Scanner;):

Scanner in Console = new Scanner(System.in);

float fFuel_n; //declare a temporary variable to hold the user input

for fuel amount

fFuel_n = inConsole.nextFloat();//Read the Fuel amount

Repeat (and adapt) above code to read all the user inputs.

6. Now add the code that implements your strategy of calculating the afc and ac.

7. Finally, add three System.out.println() statements that state the overall afc, ac and the

warning message if ac exceeds the 16cent threshold.

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

threshold value and number of fillings.

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 a 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?

Please refer to the Java Assignment Marking Rubric for details on marks.

IIT/IIT G Java Assignment 2018 S2 r0

Stage 2

As the user input and program output via the console is not very satisfactory from a humancomputer

interaction and usability point of view, your task in this stage is to design and

implement a Java Swing GUI application (using the built-in WindowBuilder in Eclipse and

Java Swing components) that provides an easy to use interface.

This GUI application must allow a user to input the various data elements. 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 final results, and

an Exit or Quit button to properly close the program.

Use the same code for the calculations from 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 may 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. You are free to use your own layout and

other GUI elements, as long as the functionality is correct.

IIT/IIT G Java Assignment 2018 S2 r0

Notes:

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 zero as discussed earlier. Checking for invalid user

input will be discussed in lectures later in the term.

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 labels “Average Fuel Consumption“, “Average

Cost” and another label to show a warning if the average cost is higher 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 a 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 Rubric for details on marks.

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.

(See below for a screenshot.)

IIT/IIT G Java Assignment 2018 S2 r0

3. As in the lectures, workshops and lab classes, give that Java application a suitable name

– Stage2 – (and optionally package name) of your choice.

IIT/IIT G Java Assignment 2018 S2 r0

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

IIT/IIT G Java Assignment 2018 S2 r0

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

IIT/IIT G Java Assignment 2018 S2 r0

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 for afc and ac.

9. Reuse your code for the calculation 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 fuel.txt contains the car data for several cars in the fleet. Each line of this file contains

the data for a single car. Each line consists of the car_name as the first element, followed by a

semicolon and five sets of amount fuel purchased, price of fuel and distance travelled. Each

element is separated by a comma. For example:

IIT/IIT G Java Assignment 2018 S2 r0

Toyota;33.0,177,412.5,45.6,55,570.0,51.6,104,430.0,25.0,50,277.8

,12.4,91,124.0

i.e. Vehicle; fuel_1, price_1, km_1, fuel_2, price_2,

km_2, fuel_3, price_3, km_3 fuel_4, price_4,

km_4, fuel_5, price_5, km_5

You will need to copy fuel.txt into the same directory of your Eclipse project that holds the

.project file. When marking, the details in the file may change, but the structure will not.

Your task will be to add code to your program that reads the car data from the text file, put these

into appropriate storage in memory (I suggest you create a data class similar to the example in

star4.java and then create an array or vector that will hold each instantiation of that data class),

add the car names to a JList object, and allows the user to choose a car from this list.

Upon this selection, the program displays the data for the currently chosen car in a text label

(JLabel), displays the overall afc, ac and the warning if ac exceeds the threshold cost, then

updates a drawing panel to display the average cost for each filling (ac_1, ac_2,…,ac_5) in a

bar graph like comparison. Finally it draws the overall average cost (ac) as a horizontal line

across the bar graph. These are new components in Stage 3 that you can add to your Stage 2

GUI or write it as a separate GUI application (either way is fine).

Notes:

? For this part of the Java assignment, add Java Swing GUI components that allow the

user to select a car name, via a JList, and that calculate the overall afc and ac as well as

draws a bar graph like comparison of the average costs of each of the five fillings in the

text file for the selected car.

The bar graph should be drawn as soon as a car name is selected in the JList. It should

show the average cost for each filling as a vertical bar starting from a common baseline

near the bottom of the drawing area.

Update the “Overall Average Fuel Consumption” and Overall Average Cost” labels

according to the information for the currently selected car by getting the relevant

information from the storage in memory (e.g. the data class) and calculating the afc and

ac.

The overall average cost (ac) for the selected car should be shown as a coloured

horizontal line across the graph. Choose a suitable colour that is different from the

colour you used for the vertical bars representing the individual average costs for each

filling.

Try to reuse code, such as the code for the drawing, from Stage 1 and Stage 2. 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.

The drawing area must have a minimum size of 300 x 200 pixels (but can be bigger).

The drawing area should have a clearly visible border, but the bars / rectangles and lines

not.

IIT/IIT G Java Assignment 2018 S2 r0

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. For example,

consider the width of the bar graphs to be a constant.

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 display of car information 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 the preferred way.

Stage 4

Here, the input will now come from an SQL database contained in the MS Access file

fuel.mdb. This file is available on the IIT / IIT G site on Canvas.

There is one table in the database, tblCars.

The table tblCars contains fields “carName”, “fuel_1”, “price_1”, “km_1”,

“fuel_2”, “price_2”, “km_2”, “fuel_3”, “price_3”, “km_3”,

“fuel_4”, “price_4”, “km_4”, “fuel_5”, “price_5”, “km_5”,

A typical record would be

<Toyota,33.0,177,412.5,45.6,55,570.0,51.6,104,430.0,25.0,50,277.

8,12.4,91,124.0>.

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 car (e.g. from a JList) and display the car usage details in

the drawing area as in Stage 3. Update the labels in the GUI showing the afc, ac, and the

warning message if ac exceeds the threshold.

Create a database report consisting of all cars’ afc and ac and present the report with the

following columns: “Car Name”, “Average Fuel Consumption (l/km)”, and “Average

Cost (cents/km)”. The report should be in ascending alphabetical order of “Car Name”. It

should be written to a file “database_report.txt”. Make sure that your columns

are properly aligned. Text columns should be left aligned, number columns right aligned.

Notes:

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

IIT/IIT G Java Assignment 2018 S2 r0

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 store all database information in local storage.

Database Report for Stage 4

Each database 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

lines.

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 …)

Correct connection to the database.

Correct identification of all the different cars and their related data.

Correct visualisation of the average costs of each filling as a bar graph for the selected

car in the drawing area as in Stage 3.

Make sure that the lines in the database reports are split into pages and the columns are

lined up and correctly formatted.

IIT/IIT G Java Assignment 2018 S2 r0

Java Style Guide

General

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.

Names

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

IIT/IIT G Java Assignment 2018 S2 r0

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 field

text box

label

list box

combo box

command button

radio button

check box

panel

track bar / slider

jTextField

jTextArea

jLabel

jList

jComboBox

jButton

jRadioButton

jCheckBox

jPanel

jSlider

jTextField_Quantity

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

Example:

newSum = sum(alpha, beta, gamma)

or

newSum = sumOfStudents(alpha, beta, gamma)

rather than

newSum = computeSum(alpha, beta, gamma)

3. Names of methods should be imperative verbs

Example:

printResults(newSum, alpha, beta)

rather than

results(newSum, alpha, beta, gamma)

IIT/IIT G Java Assignment 2018 S2 r0

4. Names of Boolean functions should be adjectives or adjectival phrases

Example:

if (empty(list))

or

if (isEmpty(list))

rather than

if (checkIfEmpty(list))

Comments

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 end-of-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.

Prologue

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: 21 Feb 2018

when it was last changed // Date last changed: 21 Mar 2018

what it does // This program does...

what files it reads / writes // Input: sample.txt, Output: none

IIT/IIT G Java Assignment 2018 S2 r0

Constants

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 iFine = 80;

use

public static final int SPEEDING_FINE = 80;

...

iFine = 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.

Method

encapsulates a task

name should be a verb. Example: printReport()

should only do 1 task.

Function

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.

IIT/IIT G Java Assignment 2018 S2 r0

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.

Types

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

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.


版权所有:编程辅导网 2021 All Rights Reserved 联系方式:QQ:99515681 微信:codinghelp 电子信箱:99515681@qq.com
免责声明:本站部分内容从网络整理而来,只供参考!如有版权问题可联系本站删除。 站长地图

python代写
微信客服:codinghelp