comp1 programming revision: java - computing at · pdf fileaqa as computing: programming in...

28
AQA AS Computing: Programming in Java 1.1 Mr MacInnes, Trinity School Nottingham Page 1 of 28 COMP1 Programming Revision: Java Contents Overview ................................................................................................................................................. 2 Variables: Declaration, Assignment and Initiation .................................................................................. 2 Output using AQAConsole ...................................................................................................................... 3 Input using AQAConsole ......................................................................................................................... 3 Constants ................................................................................................................................................ 3 Data types ............................................................................................................................................... 4 Converting data types ............................................................................................................................. 4 If statements ............................................................................................................................................ 5 If-Else statements ................................................................................................................................... 5 If-Else If-Else statements ........................................................................................................................ 6 Switch ...................................................................................................................................................... 7 For loop ................................................................................................................................................... 7 Foreach loop ........................................................................................................................................... 8 Do...While loop ........................................................................................................................................ 8 While loop................................................................................................................................................ 8 Java Constructor Function ...................................................................................................................... 9 Functions ............................................................................................................................................... 10 Create................................................................................................................................................ 10 Parameters ........................................................................................................................................ 10 Call .................................................................................................................................................... 11 Procedures ............................................................................................................................................ 11 Create................................................................................................................................................ 11 Parameters ........................................................................................................................................ 11 Call .................................................................................................................................................... 12 One-dimensional arrays ........................................................................................................................ 12 Two-dimensional arrays ........................................................................................................................ 13 Write to a text file using AQAWriteTextFile – Rewrite file ..................................................................... 14 Write to a text file using AQAWriteTextFile – Append to end of file ..................................................... 15 Read from a text file using AQAReadTextFile ...................................................................................... 16 Write to a CSV file using AQAWriteTextFile – Rewrite file ................................................................... 17 Write to a CSV file using AQAWriteTextFile – Append to end of file .................................................... 18 Read from a CSV file using AQAReadTextFile..................................................................................... 20

Upload: buinhu

Post on 07-Mar-2018

229 views

Category:

Documents


4 download

TRANSCRIPT

AQA AS Computing: Programming in Java 1.1 Mr MacInnes, Trinity School Nottingham

Page 1 of 28

COMP1 Programming Revision: Java

Contents Overview ................................................................................................................................................. 2

Variables: Declaration, Assignment and Initiation .................................................................................. 2

Output using AQAConsole ...................................................................................................................... 3

Input using AQAConsole ......................................................................................................................... 3

Constants ................................................................................................................................................ 3

Data types ............................................................................................................................................... 4

Converting data types ............................................................................................................................. 4

If statements ............................................................................................................................................ 5

If-Else statements ................................................................................................................................... 5

If-Else If-Else statements ........................................................................................................................ 6

Switch ...................................................................................................................................................... 7

For loop ................................................................................................................................................... 7

Foreach loop ........................................................................................................................................... 8

Do...While loop ........................................................................................................................................ 8

While loop................................................................................................................................................ 8

Java Constructor Function ...................................................................................................................... 9

Functions ............................................................................................................................................... 10

Create ................................................................................................................................................ 10

Parameters ........................................................................................................................................ 10

Call .................................................................................................................................................... 11

Procedures ............................................................................................................................................ 11

Create ................................................................................................................................................ 11

Parameters ........................................................................................................................................ 11

Call .................................................................................................................................................... 12

One-dimensional arrays ........................................................................................................................ 12

Two-dimensional arrays ........................................................................................................................ 13

Write to a text file using AQAWriteTextFile – Rewrite file ..................................................................... 14

Write to a text file using AQAWriteTextFile – Append to end of file ..................................................... 15

Read from a text file using AQAReadTextFile ...................................................................................... 16

Write to a CSV file using AQAWriteTextFile – Rewrite file ................................................................... 17

Write to a CSV file using AQAWriteTextFile – Append to end of file .................................................... 18

Read from a CSV file using AQAReadTextFile..................................................................................... 20

AQA AS Computing: Programming in Java 1.1 Mr MacInnes, Trinity School Nottingham

Page 2 of 28

Write to a binary file .............................................................................................................................. 22

Read from a binary file .......................................................................................................................... 23

Linear search ........................................................................................................................................ 25

Bubble sort ............................................................................................................................................ 26

Error-handling: Try-catch ...................................................................................................................... 27

Overview For AS Computing you need to have a clear understanding of basic programming principles and structure. This document contains all of the code that has been covered throughout the year. You should use this as a revision aid for the exam, but it can also be used as a reference document for any Java programming that you attempt further on, particularly in A2 Computing.

All of the code contained in this document can be found in a NetBeansProject on the Student Dropbox at:

• H:\Subjects & Departments\Computing\Programming\Java\NetbeansProjects\ COMP1 Programming Revision

It is entitled ‘COMP1 Programming Revision’. Simply copy this folder to your own NetBeansProjects folder in your user area and open it in NetBeans.

Note: If you try to run the project, it may not work as there are a lot of different pieces of code. You should use this more as a reference along with this document.

Variables: Declaration, Assignment and Initiation String name; //Declaration – create space in memory boolean drivingLicense; //Declaration – create space in memory name = "Bob"; //Assignment – set the memory space a value drivingLicense = true; //Assignment – set the memory space a value int age = 17; //Initiation – create a space in memory and set a value String town = "Nottingham";//Initiation – create a space in memory and set a value

AQA AS Computing: Programming in Java 1.1 Mr MacInnes, Trinity School Nottingham

Page 3 of 28

Output using AQAConsole AQAConsole console = new AQAConsole(); //Create the console object console.println("This is printed with a new line character."); console.print("This is printed with no new line character."); console.println(); //Prints a blank new line

Input using AQAConsole AQAConsole console = new AQAConsole(); //Creates the console object String name; //Declare String variable name int age; //Declare Integer variable age char drivingLicense; //Declare Character variable drivingLicense console.readLine(); //Reads String input with no prompt name = console.readLine("What is your name?"); //Outputs the prompt and reads next String input age = console.readInteger("What is your age?"); //Outputs the prompt and reads next Integer input drivingLicense = console.readChar("Do you have a driving license? (Y/N)"); //Outputs the prompt and reads next Character input

Constants final double PI = 3.1416; //initialises a variable that cannot be modified within the program final float VAT = 20.0f; //initialises a variable that cannot be modified within the program

AQA AS Computing: Programming in Java 1.1 Mr MacInnes, Trinity School Nottingham

Page 4 of 28

Data types

Type Identifier Bytes Values Default Value Wrapper Class

character Char 2 Unicode 2.0 (e.g. ‘A’, ‘b’, ‘9’) '\u0000' Character

8-bit integer byte 1 -128 to 127 0 Byte

short integer short 2 -32768 to 32767 0 Short

integer int 4 -2,147,483,648 to +2,147,483,647 0 Integer

long integer long 8 -9223372036854775808 to

9223372036854775808 0L Long

Real (single

precision) float 4 approx. -3.4 × 1038 to approx. 3.4 ×

1038 0.0f Float

Real (double

precision) double 8 approx. -1.7 × 10308 to approx. 1.7 ×

10308 0.0d Double

Boolean boolean 4 true or false false Boolean

String forename = "Bob"; int salary = 29999; byte years = 20; char gender = 'm'; //note the single quotes short numberPupils = 1349; long countryDebtInThousands = 935580000; float zeroCelsiusInKelvin = -273.15f; //note the 'f' double cdCost = 9.99; boolean hasDrivingLicense = true;

Converting data types int number = 15; String answer = String.valueOf(number); //convert from Integer to String String score = "150"; int scoreAnswer = Integer.valueOf(score); //convert from String to Integer String input = "true"; boolean result = Boolean.parseBoolean(input); //convert from String to Boolean

AQA AS Computing: Programming in Java 1.1 Mr MacInnes, Trinity School Nottingham

Page 5 of 28

If statements boolean success = true; int userAge = 21; String arnieSays = "I'll be back!"; if (success == true){ //if boolean success equals true console.print("Success!"); } if (success){ //if boolean success equals true console.print("Success!"); } if (userAge == 21){ //if integer userAge equals 21 console.print("Success!"); } if (userAge > 20){ //if integer userAge is more than 20 console.print("Success!"); } if (arnieSays.equals("I'll be back!")){ //if string arnieSays is the same as "I'll be back!" console.print("Success!"); }

If-Else statements boolean test = true; int pupils = 21; String country = "UK"; if (test){ //if boolean test equals true console.println("Success!"); } else { //else if boolean test does not equal true console.println("Fail!"); } if (pupils >= 21){ //if pupil age is more than or equal to 21 console.println("Success!"); } else { //else if pupil age is less than 21 (not more than or equal to 21) console.println("Fail!"); } if (country.equals("France") == false){ //if string country does not equal France console.println("Success!"); } else { //else if string country does equal france

AQA AS Computing: Programming in Java 1.1 Mr MacInnes, Trinity School Nottingham

Page 6 of 28

console.println("Fail!"); } if (!country.equals("France")){ //if string country does not equal France console.println("Success!"); } else { //else if string country does equal france console.println("Fail!"); }

If-Else If-Else statements int mark = 57; if (mark < 40){ //if the mark is less than 40 console.println("Fail"); } else if ((mark >= 40) && (mark < 50)){ //if the mark is more than or equal to 40 or less than 50 console.println("E"); } else if ((mark >= 50) && (mark < 60)){ //if the mark is more than or equal to 50 or less than 60 console.println("D"); } else if ((mark >= 60) && (mark < 70)){ //if the mark is more than or equal to 60 or less than 70 console.println("C"); } else if ((mark >= 70) && (mark < 80)){ //if the mark is more than or equal to 70 or less than 80 console.println("B"); } else if ((mark >= 80) && (mark < 90)){ //if the mark is more than or equal to 80 or less than 90 console.println("A"); } else { //for anything else (so over 89) console.println("A*"); }

AQA AS Computing: Programming in Java 1.1 Mr MacInnes, Trinity School Nottingham

Page 7 of 28

Switch String gameResult; int points = 1; switch (points){ //switch case based upon integer points case 3: //if points equals 3 gameResult = "Win"; break; //exit the switch statement case 1: //if points equals 1 gameResult = "Drawn"; break; //exit the switch statement default: //for anything else gameResult = "Loss"; break; //exit the switch statement }

For loop AQAConsole console = new AQAConsole(); //Create the object int count; for(count = 0; count < 5; count++){ //loop 5 times (from 0 up to 4); add 1 each step console.writeLine(count); } for(int i = 9; i >= 0; i--){ //loop 10 times (from 9 down to and including 0); subtract 1 each step console.writeLine(i); } int [] numbers = {1,2,3,4,5}; //Integer array of numbers int sum = 0; for(int i = 0; i < numbers.length; i++ ){ //loop from the start of the array (index 0) to the last element (1 less than the array length) sum = sum + numbers[i]; console.println("Sum: " + sum); }

AQA AS Computing: Programming in Java 1.1 Mr MacInnes, Trinity School Nottingham

Page 8 of 28

Foreach loop AQAConsole console = new AQAConsole(); //Create the console object String[] users = {"Bob","Frank","Dave","Jim"}; //String array of users for(String user : users){ //loop through each element of array. Set each element as 'user' console.println(user); } int[] marks = {56,45,78,63,88,58,60,30}; //Integer array of exam marks for (int total : marks){ //loop through each element of array. Set each element as 'total' console.println(total); }

Do...While loop AQAConsole console = new AQAConsole(); String userAnswer; do { //start looping userAnswer = console.readLine("What is your name?"); //Read input as String } while (!userAnswer.equals("X")); //loop whilst String userAnswer is not the same as 'X' int equationResult; String equation = "What is x? 3x = 6"; do { //start looping equationResult = console.readInteger(equation); //Read input as Integer } while (equationResult != 2); //loop whilst Integer equationResult is not 2

Note: a Do..While loop will execute the contents of the loop at least once.

While loop AQAConsole console = new AQAConsole(); //Create the console object String contestantName = ""; contestantName = console.readLine("Enter a name, X to finish");

AQA AS Computing: Programming in Java 1.1 Mr MacInnes, Trinity School Nottingham

Page 9 of 28

while (!contestantName.equals("X")){ console.writeLine("Entered name: " + contestantName); }

Note: a While loop will only execute the contents of the loop when certain conditions are met

Java Constructor Function public class Main { //Class is named Main public static void main(String[] args) { //Constructor method Main main = new Main(); //Direct the program to the function that contains the main program statements } public Main(){ //Function containing main program statements. Name is the same as the class name.

} }

public class Messenger { //Class is named Messenger public static void main(String[] args) { //Constructor method Messenger messenger = new Messenger (); //Direct the program to the function that contains the main program statements } public Messenger (){ //Function containing main program statements. Name is the same as the class name.

} }

Note: it is necessary to direct the Constructor main to a method of the same name as the class when using multiple methods in Java.

AQA AS Computing: Programming in Java 1.1 Mr MacInnes, Trinity School Nottingham

Page 10 of 28

Functions Note 1: functions are methods that return a value.

Note 2: for the following examples, the Constructor code is the same as the first example in Java Constructor Function

Create

String userName(){ //function name is 'userName'; data returned will be of String data type AQAConsole console = new AQAConsole(); //Create the console object String userName = ""; boolean validName = false; //boolean flag for the loop (false means no name; true means name has been entered do { //start loop userName = console.readLine("What is your name?"); //get input from user if(!userName.isEmpty()){ //check if username is not empty validName = true; //username is not empty so set boolean flag to true } else { validName = false; //username is empty so make sure boolean flag is false } } while (!validName); //loop while boolean flag is false return userName; //return username }

Parameters

double calculateVAT(double $amount){ //function name is 'calculateVAT'; data returned will be of double data type; it requires a parameter of double data type double amountVAT = 0; //sets up amountVAT double VATrate = 0.20; //sets the VATrate amountVAT = $amount * VATrate; //performs the calculation return amountVAT; //returns amountVAT }

AQA AS Computing: Programming in Java 1.1 Mr MacInnes, Trinity School Nottingham

Page 11 of 28

Call

String playerOneName = ""; playerOneName = userName(); //call function userName which returns data as a String

double orderVAT; orderVAT = calculateVAT(27.45); //call function calculateVAT which returns data as a double; passes a parameter of double data type

Procedures Note 1: procedures are methods that don’t return a value.

Note 2: for the following examples, the Constructor code is the same as the first example in Java Constructor Function

Create

void welcomeMessage(){ //procedure name is 'welcomeMessage'; void indicates that nothing is returned AQAConsole console = new AQAConsole(); //Create the console object console.println(); console.println("Welcome to COMP1 Programming Revision"); //prints output console.println(); }

Parameters

void personalisedGreeting(String $name){ //procedure name is 'personalisedGreeting'; void indicates that nothing is returned; it requires a parameter of String data type AQAConsole console = new AQAConsole(); //Create the console object console.println(); console.println("Hello " + $name); //prints 'Hello ' and the parameter String $name console.println(); }

AQA AS Computing: Programming in Java 1.1 Mr MacInnes, Trinity School Nottingham

Page 12 of 28

Call

welcomeMessage(); //call procedure welcomeMessage String $studentName; AQAConsole console = new AQAConsole; //Create the console object $studentName = console.readLine("Enter your name: "); //retrieve the $studentName from the user personalisedGreeting($studentName); //call procedure personalisedGreeting; passes a parameter of String data type

One-dimensional arrays AQAConsole console = new AQAConsole; //Create the console object String[] tutorGroup = {"Fred", "Jack", "Chris", "Ali"}; //initialises (create and set values) a one-dimensional array of String data type; console.println(tutorGroup[0]); //prints out 'Fred' console.println(tutorGroup[1]); //prints out 'Jack' console.println(tutorGroup[2]); //prints out 'Chris' console.println(tutorGroup[3]); //prints out 'Ali' AQAConsole console = new AQAConsole; //Create the console object int teamSize = 4; //initialise variable of teamSize int[] playerNumbers = new int[teamSize]; //declares a one-dimensional array of Integer data type sized 4 elements (0 to 3) for (int j = 0; j < teamSize; j++){ //loop through array (from 0 to teamSize) playerNumbers[j] = console.readInteger("Enter a player number"); //input a number for each element } //end loop console.println(playerNumbers[0]); //prints out index 0 console.println(playerNumbers[1]); //prints out index 1

AQA AS Computing: Programming in Java 1.1 Mr MacInnes, Trinity School Nottingham

Page 13 of 28

Two-dimensional arrays AQAConsole console = new AQAConsole(); String[][] studentDetails = new String[3][3]; //declare a two-dimensional array of String data type size 3 by 3 (0 to 2; 0 to 2) //Set details for student index 0 studentDetails[0][0] = "Bob"; //student name studentDetails[0][1] = "10MI"; //student form studentDetails[0][2] = "Mr and Mrs Bob"; //student guardians //Set details for student index 1 studentDetails[1][0] = "Frank"; //student name studentDetails[1][1] = "10WJ"; //student form studentDetails[1][2] = "Mr and Mrs Frank"; //student guardians //Set details for student index 2 studentDetails[2][0] = "Henry"; //student name studentDetails[2][1] = "10AE"; //student form studentDetails[2][2] = "Mr and Mrs Henry"; //student guardians for (int k = 0; k < 3; k++){ //loop through first index (0 to 2) console.println("Name: " + studentDetails[k][0]); //print name (0) of current student (k) console.println("Form: " + studentDetails[k][1]); //print form (1) of current student (k) console.println("Guardians: " + studentDetails[k][1]); //print guardians (2) of current student (k) } for (int l = 0; l < 3; l++){ for (int m = 0; m < 3; m++){ console.println(studentDetails[l][m]); //loop through both indexes and print } }

AQA AS Computing: Programming in Java 1.1 Mr MacInnes, Trinity School Nottingham

Page 14 of 28

Write to a text file using AQAWriteTextFile – Rewrite file Note 1: To use AQAWriteTextfile you need to make sure you have the AQAWriteTextFile.java file in the project. If it is in the project, you will be able to see it next to the main java file for the program. If you cannot see it, you will need to copy it into the ‘src’ folder of this project inside your ‘NetBeansProjects’ folder.

AQAWriteTextFile writeToFile = new AQAWriteTextFile(); //creates AQAWriteTextFile object String filename = "myFile.txt"; //initialises String variable filename writeToFile.openFile(filename); //open a connection to the file String contentsToWrite1 = "This is the first line to write to the file"; //initialises String variable String contentsToWrite2 = "This is the second line"; //initialises String variable String contentsToWrite3 = "This is the third line"; //initialises String variable writeToFile.writeToTextFile(contentsToWrite1); //writes variables on a new line of the file writeToFile.writeToTextFile(contentsToWrite2); //writes variables on a new line of the file writeToFile.writeToTextFile(contentsToWrite3); //writes variables on a new line of the file writeToFile.closeFile(); //closes the connection to the file (very important)

Note 2: If ‘myFile.txt’ does not exist, then this code will create the file. You will be able to find the file in the folder for this project within ‘NetBeansProjects’.

Note 3: Each time this code is called, the contents of the file will be deleted before the content is written to the file. You need to think about whether you need to keep the existing contents before writing the new contents or not.

AQA AS Computing: Programming in Java 1.1 Mr MacInnes, Trinity School Nottingham

Page 15 of 28

Write to a text file using AQAWriteTextFile – Append to end of file Note 1: To use AQAWriteTextfile you need to make sure you have the AQAWriteTextFile.java file in the project. If it is in the project, you will be able to see it next to the main java file for the program. If you cannot see it, you will need to copy it into the ‘src’ folder of this project inside your ‘NetBeansProjects’ folder.

AQAWriteTextFile writeToFile = new AQAWriteTextFile(); //creates AQAWriteTextFile object String filename = "myFile.txt"; //initialises String variable filename writeToFile.openFile(filename, true); //open a connection to the file; true indicates that this connection will append to the file String contentsToAppend1 = "Appending line 1"; //initialises String variable String contentsToAppend2 = "Appending line 2"; //initialises String variable String contentsToAppend3 = "Appending line 3"; //initialises String variable writeToFile.writeToTextFile(contentsToAppend1); //writes variables on a new line of the file writeToFile.writeToTextFile(contentsToAppend2); //writes variables on a new line of the file writeToFile.writeToTextFile(contentsToAppend3); //writes variables on a new line of the file writeToFile.closeFile(); //closes the connection to the file (very important)

Note 2: If ‘myFile.txt’ does not exist, then this code will create the file. You will be able to find the file in the folder for this project within ‘NetBeansProjects’.

Note 3: Appending means that new content will be added at the end of the file. Therefore existing content will not be deleted. You need to think about whether you need to keep the existing contents before writing the new contents or not.

AQA AS Computing: Programming in Java 1.1 Mr MacInnes, Trinity School Nottingham

Page 16 of 28

Read from a text file using AQAReadTextFile Note 1: To use AQAReadTextfile you need to make sure you have the AQAReadTextfile.java file in the project. If it is in the project, you will be able to see it next to the main java file for the program. If you cannot see it, you will need to copy it into the ‘src’ folder of this project inside your ‘NetBeansProjects’ folder.

AQAConsole console = new AQAConsole(); AQAReadTextFile readFromFile = new AQAReadTextFile(); //creates AQAReadTextFile object String filename = "myFile.txt"; //initialises String variable filename readFromFile.openTextFile(filename); //open a connection to the file String lineContents = readFromFile.readLine(); //initialise String lineContents as first line of the file while (lineContents != null){ //start looping through file contents; loop while current line of the file is not null (null means EOF - End Of File) console.println(lineContents); //outputs the current line of the file lineContents = readFromFile.readLine(); //read next line of the file } //end loop; pointer automatically moves to the next line of the file readFromFile.closeFile(); //closes the connection to the file (very important)

Note 2: If ‘myFile.txt’ does not exist, then this code will break. The file needs to be in the folder for this project within ‘NetBeansProjects’. To improve this code, you should use a Try-Catch block to catch errors for when the file cannot be found.

AQA AS Computing: Programming in Java 1.1 Mr MacInnes, Trinity School Nottingham

Page 17 of 28

Write to a CSV file using AQAWriteTextFile – Rewrite file Note 1: To use AQAWriteTextfile you need to make sure you have the AQAWriteTextFile.java file in the project. If it is in the project, you will be able to see it next to the main java file for the program. If you cannot see it, you will need to copy it into the ‘src’ folder of this project inside your ‘NetBeansProjects’ folder.

AQAWriteTextFile writeToFile = new AQAWriteTextFile(); //creates AQAWriteTextFile object String filename = "myFile.txt"; //initialises String variable filename writeToFile.openFile(filename); //open a connection to the file //Initialise data to be stored - student names, forms and scores String name1 = "Bob"; //initialises String variable to store student 1's name String form1 = "10MI"; //initialises String variable to store student 1's form int score1 = 67; //initialises Integer variable to store student 1's score; must be converted to String before/when being written String name2 = "Phil"; //initialises String variable to store student 2's name String form2 = "10AE"; //initialises String variable to store student 2's form int score2 = 55; //initialises Integer variable to store student 2's score; must be converted to String before/when being written String name3 = "Dave"; //initialises String variable to store student 3's name String form3 = "10WJ"; //initialises String variable to store student 3's form int score3 = 72; //initialises Integer variable to store student 3's score; must be converted to String before/when being written //Write student CSV data to file writeToFile.writeToTextFile(name1+","+form1+","+ Integer.toString(score1)); //writes student 1 CSV line - data separated by commas - no comma at the end of the line writeToFile.writeToTextFile(name2+","+form2+","+ Integer.toString(score2)); //writes student 2 CSV line - data separated by commas - no comma at the end of the line

AQA AS Computing: Programming in Java 1.1 Mr MacInnes, Trinity School Nottingham

Page 18 of 28

writeToFile.writeToTextFile(name3+","+form3+","+ Integer.toString(score3)); //writes student 3 CSV line - data separated by commas - no comma at the end of the line writeToFile.closeFile(); //closes the connection to the file (very important)

Note 2: If ‘myFile.txt’ does not exist, then this code will create the file. You will be able to find the file in the folder for this project within ‘NetBeansProjects’.

Note 3: Each time this code is called, the contents of the file will be deleted before the content is written to the file. You need to think about whether you need to keep the existing contents before writing the new contents or not.

Note 4: Each piece of data on a line is separated by a comma. There is no comma at the end of the line. Each line is separated by the standard ‘new line’ character.

Note 5: Each piece of data is set as String data type before being written to the file. Other data types will need to be converted to String data type.

Write to a CSV file using AQAWriteTextFile – Append to end of file Note 1: To use AQAWriteTextfile you need to make sure you have the AQAWriteTextFile.java file in the project. If it is in the project, you will be able to see it next to the main java file for the program. If you cannot see it, you will need to copy it into the ‘src’ folder of this project inside your ‘NetBeansProjects’ folder.

AQAWriteTextFile writeToFile = new AQAWriteTextFile(); //creates AQAWriteTextFile object String filename = "myFile.txt"; //initialises filename writeToFile.openFile(filename, true); //open a connection to the file; true indicates that connection will append to file //Initialise data to be stored - product names, categories and price String productName1 = "Queen Greatest Hits"; //initialises String variable to store product 1's name String category1 = "CD"; //initialises String variable to store product 1's category double price1 = 8.99; //initialises double variable to store student 1's price String productName2 = "Sons of Anarchy"; //initialises String variable to store product 2's name String category2 = "Blu-Ray"; //initialises String variable to store product 2's category double price2 = 15.99; //initialises double variable to store student 2's price

AQA AS Computing: Programming in Java 1.1 Mr MacInnes, Trinity School Nottingham

Page 19 of 28

String productName3 = "NHL 11"; //initialises String variable to store product 3's name String category3 = "Xbox 360"; //initialises String variable to store product 3's category double price3 = 34.99; //initialises double variable to store student 3's price //Write student CSV data to file writeToFile.writeToTextFile(productName1+","+category1+","+Double.toString(price1)); //writes product 1 CSV line - data separated by commas - no comma at the end of the line writeToFile.writeToTextFile(productName2+","+category2+","+Double.toString(price2)); //writes product 2 CSV line - data separated by commas - no comma at the end of the line writeToFile.writeToTextFile(productName3+","+category3+","+Double.toString(price3)); //writes product 3 CSV line - data separated by commas - no comma at the end of the line writeToFile.closeFile(); //closes the connection to the file (very important)

Note 2: If ‘myFile.txt’ does not exist, then this code will create the file. You will be able to find the file in the folder for this project within ‘NetBeansProjects’.

Note 3: Appending means that new content will be added at the end of the file. Therefore existing content will not be deleted. You need to think about whether you need to keep the existing contents before writing the new contents or not.

Note 4: Each piece of data on a line is separated by a comma. There is no comma at the end of the line. Each line is separated by the standard ‘new line’ character.

Note 5: Each piece of data is set as String data type before being written to the file. Other data types will need to be converted to String data type.

AQA AS Computing: Programming in Java 1.1 Mr MacInnes, Trinity School Nottingham

Page 20 of 28

Read from a CSV file using AQAReadTextFile Note 1: To use AQAReadTextfile you need to make sure you have the AQAReadTextfile.java file in the project. If it is in the project, you will be able to see it next to the main java file for the program. If you cannot see it, you will need to copy it into the ‘src’ folder of this project inside your ‘NetBeansProjects’ folder.

AQAConsole console = new AQAConsole(); AQAReadTextFile readFromFile = new AQAReadTextFile(); //creates AQAReadTextFile object String filename = "myFile.txt"; //initialises String variable filename String[] valuesOnLine = new String[3]; //initialise String array sized 3 elements to temporarily store each CSV data int charNumber; //declares counter variable charNumber readFromFile.openTextFile(filename); //open a connection to the file String csvLineContents = readFromFile.readLine(); //initialise String lineContents as first line of the file while (csvLineContents != null){ //start looping through file contents; loop while current line of the file is not null (null means EOF - End Of File) valuesOnLine[0] = ""; //reset element as empty valuesOnLine[1] = ""; //reset element as empty valuesOnLine[2] = ""; //reset element as empty charNumber = 0; //resets counter variable charNumber do { //start loop valuesOnLine[0] = valuesOnLine[0] + csvLineContents.substring(charNumber, charNumber + 1); //append next character to first element of array charNumber++; //add one to counter variable charNumber (to move to next character) } while (!csvLineContents.substring(charNumber, charNumber + 1).equals(",")); //loop whilst next character is not a comma charNumber++; //add one to counter variable charNumber (to get past comma) do { //start loop valuesOnLine[1] = valuesOnLine[1] + csvLineContents.substring(charNumber, charNumber + 1); //append next character to second element of array charNumber++; //add one to counter variable charNumber (to move to next character)

AQA AS Computing: Programming in Java 1.1 Mr MacInnes, Trinity School Nottingham

Page 21 of 28

} while (!csvLineContents.substring(charNumber, charNumber + 1).equals(",")); //loop whilst next character is not a comma charNumber++; //add one to counter variable charNumber (to get past comma) do { //start loop valuesOnLine[2] = valuesOnLine[2] + csvLineContents.substring(charNumber, charNumber + 1); //append next character to third element of array charNumber++; //add one to counter variable charNumber (to move to next character) } while (charNumber < csvLineContents.length()); //loop whilst counter variable charNumber is less than the length of the current line of the file console.println("Name: " + valuesOnLine[0]); //outputs the first item of data - product Name console.println("Category: " + valuesOnLine[1]); //outputs the second item of data - product Category console.println("Price: " + valuesOnLine[2]); //outputs the third item of data - product Price console.println(); //outputs an empty line csvLineContents = readFromFile.readLine(); //read next line of the file } //end loop; pointer automatically moves to the next line of the file readFromFile.closeFile(); //closes the connection to the file (very important)

Note 2: If ‘myFile.txt’ does not exist, then this code will break. The file needs to be in the folder for this project within ‘NetBeansProjects’. To improve this code, you should use a Try-Catch block to catch errors for when the file cannot be found.

Note 3: To read from a CSV file, you need to separate the pieces of data on each line of the file. The code above is one method to achieve this. There are others.

Note 4: When you read the data in from a CSV file, it is important to know the order in which the data was written so that you can process the data correctly.

Note 5: Pay particular attention to the use of the counter variable – int charNumber – in this code.

AQA AS Computing: Programming in Java 1.1 Mr MacInnes, Trinity School Nottingham

Page 22 of 28

Write to a binary file import java.io.FileOutputStream; import java.io.DataOutputStream; import java.io.IOException;

Note 1: import statements appear at the top of the code beneath the package statement.

try { //start a try-catch block //Try all of the following statements AQAConsole console = new AQAConsole(); FileOutputStream outStream; //Create the file stream object used to connect to the file DataOutputStream dataStream; //Create the data stream object used to send data of primitive type outStream = new FileOutputStream("file.txt"); //specified file dataStream = new DataOutputStream(outStream); //creates data stream object using the file stream object //Note: data must be read in the same order that it was written dataStream.writeInt(12); //write integer to the data stream dataStream.writeBoolean(true); //write boolean to data stream dataStream.writeDouble(98.7); //write double to data stream dataStream.writeUTF("Hello world!"); //Same as write String UTF encoding is more efficient than standard Strings dataStream.writeChar('Z'); //write character to data stream dataStream.flush(); //Flushing ensures that all data in the stream has reached the file. dataStream.close(); //close data stream (frees open the file) console.println("Success: writing to file."); } catch (IOException e) { //if any of the statements in the try block fail then call the following statement console.println("Error: writing to file failed."); }

Note 2: This code assumes a file called ‘file.txt’ exists.

AQA AS Computing: Programming in Java 1.1 Mr MacInnes, Trinity School Nottingham

Page 23 of 28

Note 3: The order in which the data is written is very important. To read from this file, the data needs to be read back in the same order that it was written.

Note 4: Try-Catch blocks are normally required when manipulating files.

Read from a binary file import java.io.FileInputStream; import java.io.DataInputStream; import java.io.IOException;

Note 1: import statements appear at the top of the code beneath the package statement.

try { //start a try-catch block //Try all of the following statements AQAConsole console = new AQAConsole(); //Setup variables to retrieve data int inInt; boolean inBool; double inDouble; String inStr; char inCh; //Setup streams FileInputStream inStream; DataInputStream dataStream; inStream = new FileInputStream("file.txt"); dataStream = new DataInputStream(inStream); //Read in data from dataStream //Note: data must be read in the same order that it was written inInt = dataStream.readInt(); inBool = dataStream.readBoolean(); inDouble = dataStream.readDouble(); inStr = dataStream.readUTF(); inCh = dataStream.readChar(); dataStream.close(); //close dataStream //Print out retrieved data console.println(inInt); console.println(inBool); console.println(inDouble); console.println(inStr);

AQA AS Computing: Programming in Java 1.1 Mr MacInnes, Trinity School Nottingham

Page 24 of 28

console.println(inCh); } catch (IOException e) { //if any of the statements in the try block fail then call the following statement console.println("Error: reading from file."); }

Note 2: This code assumes a file called ‘file.txt’ exists.

Note 3: The order in which the data is read is very important. To read from this file, the data needs to be read back in the same order that it was written.

Note 4: Try-Catch blocks are normally required when manipulating files.

AQA AS Computing: Programming in Java 1.1 Mr MacInnes, Trinity School Nottingham

Page 25 of 28

Linear search AQAConsole console = new AQAConsole(); String[] classNames = {"Bob", "Eric", "Andy", "Frank", "Peter", "Sean", "Dan"}; //initialise array of String data type String search = "Peter"; //initialise String variable 'search' boolean keepSearching = true; //initialise boolean flag int position = -1; //initialise Integer position variable int p = 0; //initialise Integer p variable while (keepSearching){ //start loop - while keepSearching flag is true if (search.equals(classNames[p])) { //test if search matches current element position = p; //set position to current index keepSearching = false; //set keepSearching flag to false to stop searching } else { //test failed keepSearching = true; //make sure keepSearching flag is true to keep searching } p++; //add 1 to Integer counter variable p if (p == classNames.length){ //if Integer counter variable p equals the length of classNames array then stop searching keepSearching = false; //set flag keepSearching as false to stop searching } } if (position > -1){ //if position is not -1 then search has been successful console.println("Your search was successful. It was found at element " + position + "."); } else { //search has failed console.println("Your search could not be found"); }

AQA AS Computing: Programming in Java 1.1 Mr MacInnes, Trinity School Nottingham

Page 26 of 28

Bubble sort AQAConsole console = new AQAConsole(); String[] studentNames = {"Bob", "Eric", "Andy", "Frank", "Peter", "Sean", "Dan"}; //initialise array of String data type int n = studentNames.length; //initialise Integer variable 'n' as the length of the studentNames array boolean doMore = true; //initialises boolean flag while (doMore) { //start loop - while boolean flag doMore is true n--; //subtract 1 from n doMore = false; // assume this is our last pass over the array for (int i=0; i<n; i++) { //start loop - from 0 to n if (studentNames[i].compareTo(studentNames[i+1]) > 0) { //if current element is greater than alphabetically next element String temp = studentNames[i]; //initialise String variable 'temp' as current element studentNames[i] = studentNames[i+1]; //set current element to next element studentNames[i+1] = temp; //set next element to temp doMore = true; //set flag to true because a change has been made so need to loop again } //end if } //end for loop } //end while loop for (int counter = 0; counter < studentNames.length; counter++) { //loop from 0 to length of array studentNames console.println("Element " + counter + ": " + studentNames[counter]); //print out sorted elements }

AQA AS Computing: Programming in Java 1.1 Mr MacInnes, Trinity School Nottingham

Page 27 of 28

Error-handling: Try-catch AQAConsole console = new AQAConsole(); String numberString = ""; //initialise String variable 'numberString' numberString = console.readLine("Enter a number"); //set numberString to input try { //start a try-catch block int r = Integer.valueOf(numberString); //convert the string to an Integer variable } catch (NumberFormatException e) { //if any of the statements in the try block fail then call the following statement //Conversion will fail if the user enters text (e.g. 'Hello') instead a number console.println("Error: cannot convert number."); //output error message }

AQA AS Computing: Programming in Java 1.1 Mr MacInnes, Trinity School Nottingham

Page 28 of 28

Document History 1.0 02/05/2011 Created 1.1 05/05/2011 Corrected spelling mistakes, added variable assignment to Input using

AQAConsole