COM6516

Week01-02

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/*
* HelloWorld.java
* A traditional Hello World program!
*/

// In Java, all programs reside in a class. This class is called HelloWorld,
// and should be saved in a file called HelloWorld.java. This class has a single
// method called main, which is the entry point to the program.
//
// Compiling the class with javac HelloWorld.java will produce a bytecode file
// called HelloWorld.class if compilation is successful. This bytecode can then
// be run on any machine with a java bytecode interpreter. You can run the
// bytecode in a console by typing java HelloWorld.

public class HelloWorld {
public static void main(String[] arg) {

String helloString = "Hello";
String worldString = "World!";

// In Java the System.out.println command displays the argument to the
// console. However the command below doesn't work, because helloWorldAString
// has not been declared. Try compiling this file to see what happens,
// and take a careful look at the error message that is produced.

System.out.println(helloString + " " + worldString);

// In Java, we can use the '+' operator to concatenate strings,
// so to fix this problem, either change the argument passed to the
// System.out.println method from (helloWorldString) to
// (helloString + " " + worldString)
// or declare the variable helloWorldString before it is used by
// System.out.println by inserting
// String helloWorldString = helloString + " " + worldString;

// In Java a variable can be declared anywhere in the code, so it is
// possible to declare a variable just before it is used, which makes for
// code that is easier to read and understand.

// It is conventional to use mixed case for variable names and method
// names in Java, with with the first letter lower case, and then the
// first letter of each internal word in upper case -- e.g. helloString.
// Class names start with a capital letter -- e.g. HelloWorld.java

// details at: http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-135099.html

}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/*
* QuadraticSolver.java 1.1 26/08/2011
*
* Copyright (c) University of Sheffield 2011
*/

import java.math.*;

import sheffield.*;

/**
* QuadraticSolver.java
* solves quadratic equations for x given a*x*x + b*x + c = 0
* the code should be modified so that a, b, and c are input by the user
*
* @author Mark Stevenson (mark.stevenson@sheffield.ac.uk)
* @author (based on code written by Richard Clayton)
* @version 1.1 26 August 2011
*/

public class QuadraticSolver {
public static void main(String[] arg) {

// default values for coefficients a, b, and c
// initially, these are stored as both integers and float.
// int aInt = 1, bInt = 2000000, cInt = 1;
// double aFloat = 1, bFloat = 2000000, cFloat = 1;

EasyReader keyboard = new EasyReader();

double aFloat = keyboard.readDouble("Input a value for a: ");
double bFloat = keyboard.readDouble("Input a value for b: ");
double cFloat = keyboard.readDouble("Input a value for c: ");

// declare variables to store the two values of x that satisfy the equation
double x1, x2;

// work out the solution with int types
// aInt -= 1/2;
// x1 = (-1 * bInt + Math.sqrt(bInt*bInt - 4 * aInt * cInt)) / (2 * aInt);
// x2 = (-1 * bInt - Math.sqrt(bInt*bInt - 4 * aInt * cInt)) / (2 * aInt);
// System.out.println("Solution with integer types is x1 = " + x1 + ", and x2 = " + x2 );

// work out the solution with double types
// aFloat -= 0.5;
x1 = (-1 * bFloat + Math.sqrt(bFloat * bFloat - 4 * aFloat * cFloat)) / (2 * aFloat);
x2 = (-1 * bFloat - Math.sqrt(bFloat * bFloat - 4 * aFloat * cFloat)) / (2 * aFloat);
System.out.println("Solution with double types is x1 = " + x1 + ", and x2 = " + x2);

System.out.println("a*x1*x1 + b*x1 + c = " + (aFloat * x1 * x1 + bFloat * x1 + cFloat));
System.out.println("a*x2*x2 + b*x2 + c = " + (aFloat * x2 * x2 + bFloat * x2 + cFloat));

} //main
} // class QuadraticSolver
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import sheffield.*;

public class CycleComputer {
public static void main(String[] args) {
EasyReader myFile = new EasyReader("./timings.txt");

int amount = myFile.readInt();
double[] timings = new double[amount]; // Unit: s

for (int i = 0; i < amount; i++) {
timings[i] = myFile.readDouble();
}

Trip myTrip = new Trip(0.665, amount, timings);

double[] speeds = myTrip.getInstantaneousSpeed();

for (int i = 0; i < amount; i++) {
System.out.printf("Instantaneous speed: %.2f km/h\n", speeds[i]);
}

System.out.printf("Max speed in journey is: %.2f km/h\n", myTrip.getMaxSpeed());

System.out.printf("Total distance travelled: %.2f km\n", myTrip.getTotalDistance());

System.out.printf("Total time taken: %.2f mins\n", myTrip.getTotalTime() / 60);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
public class Trip {
private static final double PI = 3.1415927;

private double diameter; // Unit: m

private double circumference; // Unit: m

private int rotationAmount;

private double timings[]; // Unit: s

private double speeds[]; // Unit: km/h

private double maxSpeed = 0; // Unit: km/h

private double totalDistance = 0; // Unit: m

private double totalTime = 0; // Unit: s

public Trip(double diameter, int rotationAmount, double[] timings) {
this.diameter = diameter;
this.circumference = diameter * PI;
this.rotationAmount = rotationAmount;
this.timings = timings;

calcInstantaneousSpeed();
calcMaxSpeed();
clacTotalDistance();
calcTotalTime();
}

public double getDiameter() {
return diameter;
}

public double getCircumference() {
return circumference;
}

public int getRotationAmount() {
return rotationAmount;
}

private void calcInstantaneousSpeed() {
speeds = new double[rotationAmount]; // Unit: km/h

for (int i = 0; i < rotationAmount; i++) {
speeds[i] = circumference / timings[i] * 3.6; // m/s -> km/h
}
}

private void calcMaxSpeed() {
for (int i = 0; i < rotationAmount; i++) {
maxSpeed = maxSpeed > speeds[i] ? maxSpeed : speeds[i];
}
}

private void clacTotalDistance() {
for (int i = 0; i < rotationAmount; i++) {
totalDistance += timings[i] / 3600 * speeds[i];
}
}

private void calcTotalTime() {
for (int i = 0; i < rotationAmount; i++) {
totalTime += timings[i];
}
}

public double[] getInstantaneousSpeed() {
return speeds;
}

public double getMaxSpeed() {
return maxSpeed;
}

public double getTotalDistance() {
return totalDistance;
}

public double getTotalTime() {
return totalTime;
}
}

Week 03

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*
* FoodStore.java 1.0 26/08/2011
*
* Copyright (c) University of Sheffield 2011
*/


/**
* FoodStore.java
* <p>
* A simple class used in COM6516 lab class
*/

// this line of code declares the class
public class FoodStore {
// this is the constructor, which is called when a new object is created
// the constructor name is always the same as the class name
// classes can have more than one constructor
// the constructor make take zero or more parameters
// in this case there is one parameter (int a) that is used to set the
// instance field of the class
public FoodStore(int a) {
amountStored = a;
}


// these are class methods, which enable the value of the instance
// field to be modified
// these methods have a public access modifier, because they need to
// be called by other classes
// neither class method returns anything, so the return type is void
public void depositFood(int amountToDeposit) {
depositAmount += amountToDeposit;
amountStored = amountStored + amountToDeposit;
}

public void withdrawFood(int amountToWithdraw) {
withdrawAmount += amountToWithdraw;
amountStored = amountStored - amountToWithdraw;
}

// these are accessor methods, which return the value of the
// instance field
public int getAmountStored() {
return (amountStored);
}

// this is the instance field, which is an attribute associated with
// each object of the FoodStore class
// the access modifier is private, which means that this field can
// only be accessed through the class methods
// by keeping instance fields private there is a well specified interface
// to the data associated with each object
// this approach is called encapsulation
private int amountStored;

private int depositAmount = 0;
private int withdrawAmount = 0;

public int getDepositAmount() {
return depositAmount;
}

public int getWithdrawAmount() {
return withdrawAmount;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class TestFoodStore {
public static void main(String[] args) {
// create a new FoodStore object called MyFoodStore
// by invoking the constructor
FoodStore MyFoodStore = new FoodStore(10);

// display the amount stored by calling the getAmountStored
// method associated with the MyFoodStore object
System.out.println("Contains " + MyFoodStore.getAmountStored());

System.out.println("Deposit 5 foods.");

MyFoodStore.depositFood(5);

System.out.println("Contains " + MyFoodStore.getAmountStored());

System.out.println("Withdraw 10 foods.");

MyFoodStore.withdrawFood(10);

System.out.println("Contains " + MyFoodStore.getAmountStored());
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import sheffield.*;

class FoodManage {
public static void main(String[] args) {
FoodStore MyFoodStore = new FoodStore(10);

EasyReader keyboard = new EasyReader();

int numberOfWithdrawal = 0;
int numberOfDeposit = 0;
int numberOfRefuse = 0;

while (true) {
int amount = keyboard.readInt("Food manage: ");
if (amount > 0) {
MyFoodStore.depositFood(amount);
System.out.println("Deposit " + amount + " foods.");
numberOfDeposit++;
} else if (amount < 0) {
if (MyFoodStore.getAmountStored() < -amount) {
System.out.println("Transaction refused.");
numberOfRefuse++;
} else {
MyFoodStore.withdrawFood(-amount);
System.out.println("Withdraw " + (-amount) + " foods.");
numberOfWithdrawal++;
}
} else {
System.out.println("Nothing to do.");
}

System.out.println("Total number of withdrawals: " + numberOfWithdrawal);
System.out.println("Total number of deposits: " + numberOfDeposit);
System.out.println("Total number of refused transactions: " + numberOfRefuse);

System.out.println("Total amount of food deposited: " + MyFoodStore.getDepositAmount() + " foods.");
System.out.println("Total amount of food withdrawn: " + MyFoodStore.getWithdrawAmount() + " foods.");
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
class TestBasket {
public static void main(String[] args) {
Item[] shopping = {new Item("baked beans", 0.3), new Item("tomato soup", 0.4)};
for (Item i : shopping) {
System.out.println(i.toString());
}

Basket myBasket = new Basket(shopping);

System.out.println("Total price: " + myBasket.total());
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* Basket.java
* <p>
* Part of lab class for COM6516
* Written by Mark Stevenson mark.stevenson@sheffield.ac.uk
* Based on code written by Steve Maddock
* Last modified 19 September 2014
*/

public class Basket {

// Constructor function
// Create a instance of Basket
public Basket(Item[] it) {
items = it;
}

// get total price of items in the basket
public double total() {
double tot = 0.0;
for (int i = 0; i < items.length; i++) {
tot += items[i].getPrice();
} // for loop
return tot;
}

// item collections
private Item[] items;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/**
* Item.java
* <p>
* Part of lab class for COM6516
* Written by Mark Stevenson mark.stevenson@sheffield.ac.uk
* Based on code written by Steve Maddock and Richard Clayton
*/

public class Item {
public Item(String n, double p) {
name = n;
price = p;
}

public String getName() {
return name;
}

public double getPrice() {
return price;
}

// using ukp to denote pounds sterling as unicode pound symbol
// does not display properly in MS Command Window
@Override
public String toString() {
return ("Class type: " + getClass().getTypeName() +
" Class name: " + getClass().getName() +
" Name: " + name +
" Price: " + price);
}

@Override
public boolean equals(Object obj) {
if (obj == this) return true;
if (obj == null) return false;
if (obj.getClass() != this.getClass()) return false;
if (((Item) obj).getName() == this.getName() && ((Item) obj).getPrice() == this.getPrice()) return true;
return false;
}

// equals method to be added here
//public boolean equals(Object obj) {
// check if identical objects
// must be false if parameter is null
// must be false if objects have different classes
// now we can cast and do something specific for Item
//}

// instance fields
private final double price;
private final String name;

public static void main(String[] args) {
String TESTNAME = "testObject";
double TESTPRICE = 10.0;
Item testObject = new Item(TESTNAME, TESTPRICE);
System.out.println("Name:");
System.out.println("Actual field " + testObject.getName());
System.out.println("Expected " + TESTNAME);
System.out.println("Price:");
System.out.println("Actual field " + testObject.getPrice());
System.out.println("Expected " + TESTPRICE);
}
}
1
2
3
4
5
6
7
8
9
class TestItemEquals {
public static void main(String[] args) {
Item tomato = new Item("Tomato", 0.2);

Item tomatoCopy = tomato;

System.out.println(tomato.equals(tomatoCopy));
}
}

Week 04

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Person {
String name;
String birth;

Person(String name, String birth) {
this.name = name;
this.birth = birth;
}

@Override
public String toString() {
return "Name: " + name + "\n" +
"Birth: " + birth;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Student extends Person {
private String course;

Student(String name, String birth, String course) {
super(name, birth);
this.course = course;
}

@Override
public String toString() {
return "Name: " + name + "\n" +
"Birth: " + birth + "\n" +
"Course: " + course;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Tutor extends Person {
private String office;

Tutor(String name, String birth, String office) {
super(name, birth);
this.office = office;
}

@Override
public String toString() {
return "Name: " + name + "\n" +
"Birth: " + birth + "\n" +
"Office: " + office;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class TestPerson {
public static void main(String[] args) {
Person testPerson = new Person("Walker", "1996/06/16");

System.out.println(testPerson);

Student testStudent = new Student("Neo", "1996/08/01", "COM6516");

System.out.println(testStudent);

Tutor testTutor = new Tutor("Anand", "1980/01/01", "C14");

System.out.println(testTutor);
}
}
1
2
3
4
5
public class Sheep extends Animal {
public void talk() {
System.out.println("Baaa!");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class NewAnimalTest {
public static void main(String[] args) {
Animal cow = new Cow();
Animal pig = new Pig();
Animal sheep = new Sheep();

Animal[] animals = new Animal[3];
animals[0] = cow;
animals[1] = pig;
animals[2] = sheep;

for (Animal testAnimal : animals) {
testAnimal.talk();
}
}
}
1
2
3
4
5
public abstract class Animal {
public void talk() {
System.out.println("Animals can't talk");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/*
* AnimalTest.java 1.0 01/10/2010
*
* Copyright (c) University of Sheffield 2011
*/

/**
* AnimalTest.java
* <p>
* Test class to demonstrate inheritance
*
* @author Mark Stevenson (mark.stevenson@sheffield.ac.uk)
* Original code written by Guy Brown and Richard Clayton
* @version 1.1 01 October 2010
*/

public class AnimalTest {
public static void main(String[] args) {
Cow daisy = new Cow();
Pig wilbur = new Pig();
// Animal animal = new Animal();

Animal[] farm = new Animal[4];
// farm[0] = animal;
farm[0] = daisy;
farm[1] = wilbur;

for (int i = 0; i < 2; i++) {
farm[i].talk();
} // for
} // main
}
1
2
3
public interface Drawable {
public void draw(sheffield.EasyGraphics g);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
* Shape.java
* <p>
* A simple class used in week 4 to implement an abstract superclass
*
* @version 1.1 26 August 2011
* @author Richard Clayton (r.h.clayton@sheffield.ac.uk)
*/

import sheffield.*;

public abstract class Shape implements Drawable {

// instance fields
// these could be implemented as protected (as shown in the lecture notes)
// or more safely as private, with getX and getY methods as shown here
private double x;
private double y;

public Shape() {
this(0.0, 0.0);
}

public Shape(double x, double y) {
setPosition(x, y);
}

public void setPosition(double xval, double yval) {
x = xval;
y = yval;
}

public double getX() {
return x;
}

public double getY() {
return y;
}

public abstract double area();

public abstract void draw(EasyGraphics g);

}

Week 05

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
* Multiplication table
* Create a table to show 1 to 9 multiplication.
*/
public class MultiplicationTable {

/**
* World starts here
*
* @param args Command line arguments
*/
public static void main(String[] args) {
int num = 9;
System.out.print(" |");
for (int i = 0; i < num; i++) {
System.out.printf("%4d", i + 1);
}
System.out.println();
System.out.print("---");
for (int i = 0; i < num; i++) {
System.out.print("----");
}
System.out.println("--");
for (int i = 0; i < num; i++) {
System.out.print((i + 1) + " |");
for (int j = 0; j < num; j++) {
System.out.printf("%4d", (i + 1) * (j + 1));
}
System.out.println();
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* Test Circle class
*/
public class TestCircle {
/**
* World starts here
*
* @param args Command line arguments
*/
public static void main(String[] args) {
System.out.println(Circle.PI);
System.out.println(Circle.radToDeg(3.141));

Circle myCircle = new Circle(1);
System.out.println(myCircle.toString());
System.out.println(myCircle.getClass());

Circle myCircle2 = new Circle(1);
System.out.println(myCircle.equals(myCircle2));
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/*
* Circle.java
*
* Copyright (c) University of Sheffield 2014
*/

public class Circle {

// class field
public static final double PI = 3.1415927;

// instance field
private double radius;

// constructor
public Circle(double r) {
radius = r;
}

// class method
public static double radToDeg(double angleRad) {
return angleRad * 180.0 / PI;
}

// instance methods
public double area() {
// returns area of the circle
return PI * radius * radius;
}

public double circumference() {
// returns circumference of the circle
return 2.0 * PI * radius;
}

@Override
public String toString() {
return "Circle radius: " + radius;
}

@Override
public boolean equals(Object obj) {
// Check if the two objects' class are same, then if the references are same
return obj.getClass() == this.getClass() && obj == this;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class PhDThesis extends Publication {
private int numChapters;
private String university;
private String supervisor;

PhDThesis(String title, String author, int ISBN, int numPages, int numChapters, String university, String supervisor) {
super(title, author, ISBN, numPages);
this.numChapters = numChapters;
this.university = university;
this.supervisor = supervisor;
}

@Override
public String toString() {
return super.toString() + "[numChapters=" + numChapters +
",university=\"" + university + "\",supervisor=\"" + supervisor + "\"]";
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
public class TestPublication {
public static void main(String[] args) {
Publication publication = new Publication();
Book book = new Book("Test Book", "Test Author", 10000, 1000, 100);
MagazineArticle magazineArticle = new MagazineArticle("Test Mag", "Test Author", 10001, 10, "Test Name", 1, 2, 3);
PhDThesis phDThesis = new PhDThesis("Test Title", "Neo", 10002, 100, 10, "UoS", "Anand");

System.out.println(publication.toString());
System.out.println(book.toString());
System.out.println(magazineArticle.toString());
System.out.println(phDThesis.toString());
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import java.util.ArrayList;
import java.util.Random;

/**
* Create a random number table
*/
public class RandomTable {

/**
* World starts here
*
* @param args Command line arguments
*/
public static void main(String[] args) {
Random random = new Random(0);
int num = 9;

ArrayList<Integer> columns = new ArrayList<>();
while (columns.size() < num) {
int randomNum = random.nextInt(num + 1);
if (randomNum > 0 && !columns.contains(randomNum)) {
columns.add(randomNum);
}
}

ArrayList<Integer> rows = new ArrayList<>();
while (rows.size() < num) {
int randomNum = random.nextInt(num + 1);
if (randomNum > 0 && !rows.contains(randomNum)) {
rows.add(randomNum);
}
}

System.out.print(" |");
for (int i = 0; i < num; i++) {
System.out.printf("%4d", columns.get(i));
}
System.out.println();
System.out.print("---");
for (int i = 0; i < num; i++) {
System.out.print("----");
}
System.out.println("--");
for (int i = 0; i < num; i++) {
System.out.print(rows.get(i) + " |");
for (int j = 0; j < num; j++) {
System.out.printf("%4d", rows.get(i) * columns.get(j));
}
System.out.println();
}
}
}

Week 07

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/*
* Developed by Neo on 05/11/18 11:12.
* Last modified 05/11/18 10:39.
* Copyright (c) 2018. All rights reserved.
*/

import sheffield.EasyReader;

/**
* This class can generate a walking plan for a old person
*/
public class GenerateWalkingPlan {
/**
* Program starts here.
*
* @param args command line arguments.
*/
public static void main(String[] args) {
// Ask for user's name and age for creating plan
EasyReader myReader = new EasyReader();

String name = myReader.readString("What is your name? ");
int age = myReader.readInt("Hello " + name + ", how old are you? ");

// Create a walk plan and print it
WalkingPlan newPlan = new WalkingPlan(name, age);

newPlan.generate();
newPlan.toPrint();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/*
* Developed by Neo on 05/11/18 11:10.
* Last modified 05/11/18 10:45.
* Copyright (c) 2018. All rights reserved.
*/

import java.util.Random;

/**
* This is walk plan for old person
*/
class WalkingPlan {
/**
* This plan only contains 14 days plan
*/
private static final int PLAN_DAYS = 14;
/**
* We define more than 1500 meters as hard day
*/
private static final int HARD_MODE = 1500;
/**
* If two hard days in a row, we need change second day as relax day
*/
private static final int RELAX_MODE = 1000;

/**
* User's name
*/
private String name;
/**
* User's age
*/
private int age;

/**
* Every days plan
*/
private int[] plan;
/**
* The total meters of whole plan
*/
private int total;
/**
* Average meters of this plan
*/
private long average;

/**
* Constructor method for WalkingPlan
*
* @param name user's name
* @param age user's age
*/
WalkingPlan(String name, int age) {
this.name = name;
this.age = age;

// Initialize these variables
plan = new int[PLAN_DAYS];
total = 0;
average = 0;
}

/**
* This method will generate a waling plan
*/
void generate() {
Random random = new Random();
for (int i = 0; i < PLAN_DAYS; i++) {
plan[i] = 10 * (10 + random.nextInt(240)); // Generate a int in [100, 2500)
if (i > 0) {
if (plan[i] > HARD_MODE && plan[i - 1] > HARD_MODE)
plan[i] = RELAX_MODE;
}
total += plan[i];
}
average = Math.round((double) total / PLAN_DAYS);
}

/**
* This method will print walking plan
*/
void toPrint() {
System.out.println();
System.out.println(name + "(age=" + age + ") - this is your walking plan:");
for (int i = 0; i < PLAN_DAYS; i++) {
System.out.print("Day " + (i + 1) + ": walk " + plan[i] + "m");
if (plan[i] > HARD_MODE)
System.out.println(" <--- hard");
else
System.out.println();
}

System.out.println();

System.out.println("Total number of meters walked = " + total);
System.out.println("Average number of meters walked per day = " + average);
}
}

Week 08

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/*
* Developed by Neo on 12/11/18 10:21.
* Last modified 12/11/18 10:21.
* Copyright (c) 2018. All rights reserved.
*/

import java.util.*;

public class ListStringConvert {
public static void main(String[] args) {
List<String> fixedList = Arrays.asList("elephant","lion","leopard", "tiger");
System.out.println(fixedList);
List<String> myList = new LinkedList<String>(fixedList);

// Iterator<String> iter = myList.iterator();
ListIterator<String> iter = myList.listIterator();

ArrayList<String> newList = new ArrayList<>();
while (iter.hasNext()) {
newList.add(iter.next().toUpperCase());
}

System.out.println(newList);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;

/*
HashSetTest.java

Example class that demonstrates used of HashSet Collection.
*/

public class HashSetTest {

public static void main(String args[]) {
Set<Person> people = new TreeSet<Person>(new AgeComparator());// here we declare people to be the most general type, which makes it possible to swap HashSet for TreeSet.
StringTokenizer st;
String firstName, surname, line;
int age;

// read data from file
// (The try/catch construction catches an exception, ie. error,
// if the file is not found)
try {
Scanner file = new Scanner(new File("Person.txt"));
// assume file has at least one line
// that specifies the number of records
int numData = file.nextInt();

// read in each line, and split into tokens
for (int i = 0; i < numData; i++) {
line = file.next();
st = new StringTokenizer(line, "|");
firstName = st.nextToken();
surname = st.nextToken();
age = Integer.parseInt(st.nextToken());
people.add(new Person(firstName, surname, age));
}
file.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
}

// iterate through hash set
Iterator<Person> iter = people.iterator();
while (iter.hasNext()) {
Person p = iter.next();
if (!p.getSurname().equals("James") && !p.getSurname().equals("Cole")) {
iter.remove();
}
}

Iterator<Person> iter = people.iterator();
while (iter.hasNext()) {
Person p = iter.next();
if (p.getSurname().equals("Wright-Phillips")) {
iter.remove();
}
}

// iterate through hash set
Iterator<Person> i = people.iterator();
while (i.hasNext()) {
Person p = i.next();
System.out.print(p);
System.out.print(", hash code ");
System.out.println(p.hashCode());
}

System.out.println("Using a comparator of a person class :");
Person firstPerson = people.iterator().next();//grab the first one
for (Person p : people)
System.out.println(firstPerson + " compared to " + p + " returns " + firstPerson.compareTo(p));

System.out.println("Using AgeComparator :");
Comparator<Person> comparator = new AgeComparator();
firstPerson = people.iterator().next();//grab the first one
for (Person p : people)
System.out.println(firstPerson + " compared to " + p + " returns " + comparator.compare(firstPerson, p));
}
}
1
2
3
4
5
6
7
8
import java.util.*;

public class AgeComparator implements Comparator<Person> {

public int compare(Person a, Person b) {
return b.getAge() - a.getAge();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*
Shakespeare.java

Reads information from Shakespeare.txt
*/

import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;

public class Shakespeare {

public static void main(String args[]) {
String line;
String wd;
StringTokenizer st;
List<String> words = new LinkedList<String>();

// Read data from file and split into tokens, i.e. words
// (The try/catch construction catches an exception, ie. error,
// if the file is not found)
try {
Scanner file = new Scanner(new File("Shakespeare.txt"));
// read in each line, and split into tokens
while (file.hasNext()) {
line = file.next();
st = new StringTokenizer(line, " .,:?'");
// space, full stop, comma, etc.
// are included as token delimiters
// and are thus not tokens themselves
while (st.hasMoreTokens()) {
wd = st.nextToken();
words.add(wd);
}
}
file.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
}
System.out.println("words: " + words);

for (String word : words) {
if (word.charAt(0) == 'a')
System.out.print(word + ", ");
}
System.out.println();

// Produce a sorted list
Set<String> wds = new TreeSet<String>(new StringComparator());

wds.addAll(words);

System.out.println("sorted words: " + wds);

List<String> lowerWords = new LinkedList<String>();
for (String word : words)
lowerWords.add(word.toLowerCase());

Set<String> lowerWds = new TreeSet<String>(new StringComparator());

lowerWds.addAll(lowerWords);

for (String word : lowerWds)
System.out.println(word + ": " + Collections.frequency(lowerWords, word));
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/*
* Developed by Neo on 12/11/18 11:40.
* Last modified 12/11/18 11:40.
* Copyright (c) 2018. All rights reserved.
*/

import java.util.Comparator;

public class StringComparator implements Comparator<String> {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/*
* Developed by Neo on 12/11/18 14:40.
* Last modified 12/11/18 14:40.
* Copyright (c) 2018. All rights reserved.
*/

import java.util.ArrayList;
import java.util.List;

public class ListAgain {
public static void main(String[] args) {
List<Integer> listA = new ArrayList<>();

listA.add(1);
listA.add(2);
listA.add(3);
listA.add(4);
listA.add(5);

List<Integer> listB = new ArrayList<>();

listB.add(3);
listB.add(4);
listB.add(5);
listB.add(6);
listB.add(7);

List<Integer> listC = new ArrayList<>(listA);

listC.retainAll(listB);

listA.addAll(listB);
listA.removeAll(listC);

System.out.println(listA);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/*
* Developed by Neo on 12/11/18 15:26.
* Last modified 12/11/18 15:26.
* Copyright (c) 2018. All rights reserved.
*/

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;

public class MoreList {
public static void main(String[] args) {
LinkedList<Integer> listA = new LinkedList<>();

listA.add(0);
listA.add(1);
listA.add(2);
listA.add(3);
listA.add(4);

List<Integer> listB = new ArrayList<>();

listB.add(5);
listB.add(6);
listB.add(7);
listB.add(8);
listB.add(9);

ListIterator<Integer> iteratorA;
ListIterator<Integer> iteratorB;

// 1
iteratorA = listA.listIterator();
iteratorB = listB.listIterator();

while (iteratorA.hasNext()) {
iteratorA.next();
if (iteratorB.hasNext())
iteratorA.add(iteratorB.next());
}

while (iteratorB.hasNext()) {
iteratorA.add(iteratorB.next());
}

System.out.println("List A=" + listA);
System.out.println("List B=" + listB);

// 2
iteratorB = listB.listIterator();

while (iteratorB.hasNext()) {
iteratorB.next();
if (iteratorB.hasNext()) {
iteratorB.next();
iteratorB.remove();
}
}

System.out.println("List A=" + listA);
System.out.println("List B=" + listB);

// 3
listA.removeAll(listB);

System.out.println("List A=" + listA);
System.out.println("List B=" + listB);
}
}

Week 09

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
* Developed by Neo on 19/11/18 11:54.
* Last modified 19/11/18 11:54.
* Copyright (c) 2018. All rights reserved.
*/

import javax.swing.*;
import java.awt.*;

public class CornerString extends JFrame {
public CornerString() {
super("Corner String");

//For better looks.
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Exception e) {
e.printStackTrace();
}

this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setSize(960, 480);
this.setResizable(false);
this.setLocationRelativeTo(null);

this.setContentPane(new StringPanel());

this.setVisible(true);
}

public static void main(String[] args) {
new CornerString();
}

public class StringPanel extends JPanel {
public StringPanel() {
super(new BorderLayout());

JLabel label1 = new JLabel("To be or not to be");
JLabel label2 = new JLabel("To be or not to be");
JLabel label3 = new JLabel("To be or not to be");
JLabel label4 = new JLabel("To be or not to be");

label1.setFont(new Font("Consolas", Font.PLAIN, 32));
label1.setForeground(Color.BLUE);
label2.setFont(new Font("Comic Sans MS", Font.PLAIN, 32));
label2.setForeground(Color.GREEN);
label3.setFont(new Font("Monospaced", Font.PLAIN, 32));
label3.setForeground(Color.RED);
label4.setFont(new Font("Courier", Font.PLAIN, 32));
label4.setForeground(Color.YELLOW);

JPanel northPanel = new JPanel();
northPanel.setLayout(new BoxLayout(northPanel, BoxLayout.X_AXIS));

northPanel.add(label1);
northPanel.add(Box.createHorizontalGlue());
northPanel.add(label2);

JPanel southPanel = new JPanel();
southPanel.setLayout(new BoxLayout(southPanel, BoxLayout.X_AXIS));

southPanel.add(label3);
southPanel.add(Box.createHorizontalGlue());
southPanel.add(label4);

add(northPanel, BorderLayout.NORTH);
add(southPanel, BorderLayout.SOUTH);
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/*
* Developed by Neo on 19/11/18 15:44.
* Last modified 19/11/18 15:44.
* Copyright (c) 2018. All rights reserved.
*/

import javax.swing.*;

public class GIFFrame extends JFrame {
public GIFFrame() {
super("GIF Frame");

setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

ImageIcon imageIcon = new ImageIcon("globe.gif", "globe");

setSize(imageIcon.getIconWidth(), imageIcon.getIconHeight());

JLabel imageLabel = new JLabel(imageIcon);

add(imageLabel);

setLocationRelativeTo(null);

setVisible(true);
}

public static void main(String[] args) {
new GIFFrame();
}
}

Week 10

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class MyFrame extends JFrame implements ActionListener {
private MyPanel drawingPanel;

private MyFrame() {
int width = (int) (Toolkit.getDefaultToolkit().getScreenSize().getWidth() / 2.0);
int height = (int) (width / 16.0 * 9.0);
setSize(width, height);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);

//For better looks.
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (Exception e) {
e.printStackTrace();
}

drawingPanel = new MyPanel();
drawingPanel.setPolygon(5);
Container contentPane = this.getContentPane();
contentPane.add(drawingPanel, BorderLayout.CENTER);

JPanel columnOfButtons = new JPanel(new GridLayout(8, 1));
ButtonGroup buttonGroup = new ButtonGroup();
for (int i = 3; i < 10; i++) {
makeRadioButton(columnOfButtons, String.valueOf(i), buttonGroup, this);
}

JButton exit = new JButton("Exit");
exit.addActionListener(this);
columnOfButtons.add(exit);

contentPane.add(columnOfButtons, BorderLayout.EAST);

setVisible(true);
}

public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(MyFrame::new);
}

private void makeRadioButton(JPanel p, String name, ButtonGroup group, ActionListener target) {
JRadioButton b = new JRadioButton(name);
group.add(b);
// add it to the specified JPanel and make the JPanel listen
p.add(b);
b.addActionListener(target);
}

public void actionPerformed(ActionEvent e) {
// Do the appropriate thing depending on which button is pressed.
// Use the getActionCommand() method to identify the button.
switch (e.getActionCommand()) {
case "Exit":
System.exit(0);
case "3":
drawingPanel.setPolygon(3);
break;
case "4":
drawingPanel.setPolygon(4);
break;
case "5":
drawingPanel.setPolygon(5);
break;
case "6":
drawingPanel.setPolygon(6);
break;
case "7":
drawingPanel.setPolygon(7);
break;
case "8":
drawingPanel.setPolygon(8);
break;
case "9":
drawingPanel.setPolygon(9);
break;
}
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/*
* Developed by Neo on 26/11/18 15:37.
* Last modified 17/11/17 14:21.
* Copyright (c) 2018. All rights reserved.
*/

import javax.swing.*;
import java.awt.*;

public class MyPanel extends JPanel {
private int sides = 0;

void setPolygon(int sides) {
this.sides = sides;
this.repaint();
}

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);

Graphics2D g2 = (Graphics2D) g;

g2.setColor(Color.RED);

// Make text and shapes appear smoother
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

if (sides == 0) sides = 5;
int[] x = new int[sides];
int[] y = new int[sides];

int width = getWidth();
int height = getHeight();

int r = (width > height ? height : width) / 3;

for (int i = 0; i < sides; i++) {
x[i] = (int) (width / 2 + r * Math.cos(2 * Math.PI / sides * i));
y[i] = (int) (height / 2 + r * Math.sin(2 * Math.PI / sides * i));
}
Shape shape = new Polygon(x, y, sides);

g2.draw(shape);
}
}

Week 11

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/*
* Developed by Neo on 12/8/18 7:39 PM.
* Last modified 11/24/17 2:18 PM.
* Copyright (c) 2018. All rights reserved.
*/

/*
* JCalculator.java
* Class to produce a simple calculator in a window
*/

import javax.swing.*;
import java.awt.*;

public class JCalculator extends JFrame {
private JCalculator() {
super("JCalculator");
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
setSize(300, 400);
setLocationRelativeTo(null);
Container contentPane = this.getContentPane();

JTextArea display = new JTextArea(1, 20);
display.setEditable(false);
display.setFont(new Font("Courier", Font.BOLD, 40));
display.setPreferredSize(new Dimension(300, 100));
contentPane.add(display, BorderLayout.NORTH);

CalculatorButtons buttons = new CalculatorButtons(display);
contentPane.add(buttons, BorderLayout.CENTER);

}

public static void main(String[] args) {
JFrame frm = new JCalculator();
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frm.setVisible(true);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
/*
* Developed by Neo on 12/8/18 7:48 PM.
* Last modified 11/24/17 2:18 PM.
* Copyright (c) 2018. All rights reserved.
*/

/*
* CalculatorButtons.java
* COM6516
*/

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;

class CalculatorButtons extends JPanel {

private static final String[] buttonLabels = {"7", "8", "9", "+", "4", "5", "6", "-",
"1", "2", "3", "*", "0", "=", "+/-", "/"};
private static final String[] opButtonLabels = {"+", "-", "*", "=", "+/-", "/"};

private String displayedValue = "0";
private String operand1;

private enum OP {PLUS, MINUS, MULT, DIV}

private OP operation = null;

CalculatorButtons(JTextArea display) {
setLayout(new GridLayout(4, 4));

// create buttons using factory method
for (int i = 0; i < 16; i++) {
makeButton(this, buttonLabels[i], display);
}
}

// factory method for making buttons
private void makeButton(JPanel panel, String name, JTextArea display) {
JButton button = new JButton(name);
panel.add(button);
// ADD CODE HERE TO CREATE NEW BUTTON ACTION, AND LINK BUTTON TO DISPLAY
button.addActionListener(new ButtonAction(name, display));
}

private class ButtonAction implements ActionListener {
private String theLabel;
private JTextArea theDisplay;

ButtonAction(String name, JTextArea display) {
theLabel = name;
theDisplay = display;
}

public void actionPerformed(ActionEvent actionEvent) {
if (Arrays.asList(opButtonLabels).contains(theLabel)) { //If pressed + - * / = +/-
if (theLabel.equals("=")) { //=
if (operation == null) { //No second value
//No need to update display
System.out.println("No-op " + displayedValue);
} else { //Calculate
int result = 0;
try {
switch (operation) {
case PLUS:
result = Math.addExact(Integer.parseInt(operand1), Integer.parseInt(displayedValue));
break;
case MINUS:
result = Math.subtractExact(Integer.parseInt(operand1), Integer.parseInt(displayedValue));
break;
case MULT:
result = Math.multiplyExact(Integer.parseInt(operand1), Integer.parseInt(displayedValue));
break;
case DIV:
//No need to check result if overflow
result = Integer.parseInt(operand1) / Integer.parseInt(displayedValue);
break;
}
System.out.println("Operands are " + operand1 + " and " + displayedValue);
System.out.println("Result = " + result);
displayedValue = Integer.toString(result);
theDisplay.setText(displayedValue);
} catch (ArithmeticException e) {
displayedValue = "0";
theDisplay.setText(e.getMessage());
}
operation = null;
}
} else if (theLabel.equals("+/-")) { //+/-
int temp = Integer.parseInt(displayedValue) * -1;
displayedValue = Integer.toString(temp);
theDisplay.setText(displayedValue);
} else { //+-*/
if (operation == null) { //Continue only null operation
switch (theLabel) {
case "+":
operation = OP.PLUS;
theDisplay.setText("+");
break;
case "-":
operation = OP.MINUS;
theDisplay.setText("-");
break;
case "*":
operation = OP.MULT;
theDisplay.setText("*");
break;
case "/":
operation = OP.DIV;
theDisplay.setText("/");
break;
}
operand1 = displayedValue;
displayedValue = "0";
}
}
} else { //If pressed number
if (displayedValue.equals("0"))
displayedValue = theLabel;
else {
if (displayedValue.length() < 8) //Cannot larger than 10M to prevent overflow
displayedValue += theLabel;
}

theDisplay.setText(displayedValue);
}
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
/*
* Developed by Neo on 12/8/18 7:48 PM.
* Last modified 11/24/17 2:18 PM.
* Copyright (c) 2018. All rights reserved.
*/

/*
* CalculatorButtons.java
* COM6516
*/

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;

class CalculatorButtons extends JPanel {

private static final String[] buttonLabels = {"7", "8", "9", "+", "4", "5", "6", "-",
"1", "2", "3", "*", "0", "=", ".", "/"};
private static final String[] opButtonLabels = {"+", "-", "*", "=", "/"};

private String displayedValue = "0";
private String operand1;

private enum OP {PLUS, MINUS, MULT, DIV}

private OP operation = null;

private boolean dotPressed = false;

CalculatorButtons(JTextArea display) {
setLayout(new GridLayout(4, 4));

// create buttons using factory method
for (int i = 0; i < 16; i++) {
makeButton(this, buttonLabels[i], display);
}
}

// factory method for making buttons
private void makeButton(JPanel panel, String name, JTextArea display) {
JButton button = new JButton(name);
panel.add(button);
// ADD CODE HERE TO CREATE NEW BUTTON ACTION, AND LINK BUTTON TO DISPLAY
button.addActionListener(new ButtonAction(name, display));
}

private class ButtonAction implements ActionListener {
private String theLabel;
private JTextArea theDisplay;

ButtonAction(String name, JTextArea display) {
theLabel = name;
theDisplay = display;
}

public void actionPerformed(ActionEvent actionEvent) {
if (Arrays.asList(opButtonLabels).contains(theLabel)) { //If pressed + - * / =
if (theLabel.equals("=")) { //=
if (operation == null) { //No second value
//No need to update display
System.out.println("No-op " + displayedValue);
} else { //Calculate
float result = 0;
try {
switch (operation) {
case PLUS:
result = Float.parseFloat(operand1) + Float.parseFloat(displayedValue);
break;
case MINUS:
result = Float.parseFloat(operand1) - Float.parseFloat(displayedValue);
break;
case MULT:
result = Float.parseFloat(operand1) * Float.parseFloat(displayedValue);
break;
case DIV:
result = Float.parseFloat(operand1) / Float.parseFloat(displayedValue);
break;
}
System.out.println("Operands are " + operand1 + " and " + displayedValue);
System.out.println("Result = " + result);
displayedValue = Float.toString(result);
theDisplay.setText(displayedValue);
} catch (ArithmeticException e) {
displayedValue = "0";
theDisplay.setText(e.getMessage());
}
dotPressed = true; //Because result must be float and have a "."
operation = null;
}
} else { //+-*/
if (operation == null) { //Continue only null operation
switch (theLabel) {
case "+":
operation = OP.PLUS;
theDisplay.setText("+");
break;
case "-":
operation = OP.MINUS;
theDisplay.setText("-");
break;
case "*":
operation = OP.MULT;
theDisplay.setText("*");
break;
case "/":
operation = OP.DIV;
theDisplay.setText("/");
break;
}
dotPressed = false;
operand1 = displayedValue;
displayedValue = "0";
}
}
} else { //If pressed number or "."
if (displayedValue.length() < 8) { //Prevent overflow
if (theLabel.equals(".")) { //Press "."
if (!dotPressed) {
displayedValue += theLabel;
}
dotPressed = true;
} else { //Press number
if (displayedValue.equals("0"))
displayedValue = theLabel;
else {
displayedValue += theLabel;
}
}
}
theDisplay.setText(displayedValue);
}
}
}
}

Assessed Lab 1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/*
* Developed by Neo on 05/11/18 11:12.
* Last modified 05/11/18 10:39.
* Copyright (c) 2018. All rights reserved.
*/

import sheffield.EasyReader;

/**
* This class can generate a walking plan for a old person
*/
public class GenerateWalkingPlan {
/**
* Program starts here.
*
* @param args command line arguments.
*/
public static void main(String[] args) {
// Ask for user's name and age for creating plan
EasyReader myReader = new EasyReader();

String name = myReader.readString("What is your name? ");
int age = myReader.readInt("Hello " + name + ", how old are you? ");

// Create a walk plan and print it
WalkingPlan newPlan = new WalkingPlan(name, age);

newPlan.generate();
newPlan.toPrint();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/*
* Developed by Neo on 05/11/18 11:10.
* Last modified 05/11/18 10:45.
* Copyright (c) 2018. All rights reserved.
*/

import java.util.Random;

/**
* This is walk plan for old person
*/
class WalkingPlan {
/**
* This plan only contains 14 days plan
*/
private static final int PLAN_DAYS = 14;
/**
* We define more than 1500 meters as hard day
*/
private static final int HARD_MODE = 1500;
/**
* If two hard days in a row, we need change second day as relax day
*/
private static final int RELAX_MODE = 1000;

/**
* User's name
*/
private String name;
/**
* User's age
*/
private int age;

/**
* Every days plan
*/
private int[] plan;
/**
* The total meters of whole plan
*/
private int total;
/**
* Average meters of this plan
*/
private long average;

/**
* Constructor method for WalkingPlan
*
* @param name user's name
* @param age user's age
*/
WalkingPlan(String name, int age) {
this.name = name;
this.age = age;

// Initialize these variables
plan = new int[PLAN_DAYS];
total = 0;
average = 0;
}

/**
* This method will generate a waling plan
*/
void generate() {
Random random = new Random();
for (int i = 0; i < PLAN_DAYS; i++) {
plan[i] = 10 * (10 + random.nextInt(240)); // Generate a int in [100, 2500)
if (i > 0) {
if (plan[i] > HARD_MODE && plan[i - 1] > HARD_MODE)
plan[i] = RELAX_MODE;
}
total += plan[i];
}
average = Math.round((double) total / PLAN_DAYS);
}

/**
* This method will print walking plan
*/
void toPrint() {
System.out.println();
System.out.println(name + "(age=" + age + ") - this is your walking plan:");
for (int i = 0; i < PLAN_DAYS; i++) {
System.out.print("Day " + (i + 1) + ": walk " + plan[i] + "m");
if (plan[i] > HARD_MODE)
System.out.println(" <--- hard");
else
System.out.println();
}

System.out.println();

System.out.println("Total number of meters walked = " + total);
System.out.println("Average number of meters walked per day = " + average);
}
}

Assessed Lab 2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/*
* Developed by Neo on 12/10/18 5:17 PM.
* Last modified 12/10/18 11:24 AM.
* Copyright (c) 2018. All rights reserved.
*/

import javax.swing.*;

/**
* This class will show the Scorer GUI.
*/
public class ScorerGUI {
/**
* Program starts here.
*
* @param args command line arguments
*/
public static void main(String[] args) {
JFrame f = new ScoringFrame();
//Set the frame visible
f.setVisible(true);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/*
* Developed by Neo on 12/10/18 5:17 PM.
* Last modified 12/10/18 11:24 AM.
* Copyright (c) 2018. All rights reserved.
*/

/**
* This class is a score record.
*/
class Scorer {
/**
* Scorer's name.
*/
private String name;
/**
* Scorer's score.
*/
private int score;

/**
* Constructor method of Scorer.
*
* @param name Scorer's name.
* @param score Scorer's score.
*/
Scorer(String name, int score) {
this.name = name;
this.score = score;
}

/**
* Getter method of name.
*
* @return Scorer's name.
*/
String getName() {
return name;
}

/**
* Getter method of score.
*
* @return Scorer's score.
*/
int getScore() {
return score;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/*
* Developed by Neo on 12/10/18 5:17 PM.
* Last modified 12/10/18 11:38 AM.
* Copyright (c) 2018. All rights reserved.
*/

import java.util.Comparator;

/**
* This comparator will compare two scorer's score.
*/
public class ScoreComparator implements Comparator<Scorer> {
/**
* Compare to scorer's score.
*
* @param a First scorer.
* @param b Second scorer.
* @return The difference of two scorers' score.
*/
@Override
public int compare(Scorer a, Scorer b) {
return b.getScore() - a.getScore();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
/*
* Developed by Neo on 12/10/18 5:17 PM.
* Last modified 12/10/18 11:47 AM.
* Copyright (c) 2018. All rights reserved.
*/

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Set;
import java.util.TreeSet;

/**
* This class will create a score frame.
*/
class ScoringFrame extends JFrame implements ActionListener {
/**
* "Enter Score" button.
*/
private JButton enterButton;
/**
* "Quit" button.
*/
private JButton quitButton;
/**
* Name text field.
*/
private JTextField nameText;
/**
* Score text field.
*/
private JTextField scoreText;

/**
* This label show the highest score.
*/
private JLabel highestLabel;

/**
* This set stores all scores.
*/
private Set<Scorer> scorerList;

/**
* Constructor method of ScoringFrame.
*/
ScoringFrame() {
//Set title
super("Competition score GUI");
//Set window's size
setSize(960, 270);
//Set window's position in the centre of screen
this.setLocationRelativeTo(null);
//Set this windows can only be closed by quit button
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

//Components of this frame
JLabel nameLabel = new JLabel("Name: ");
nameText = new JTextField(20);
JLabel scoreLabel = new JLabel("Score: ");
scoreText = new JTextField(5);
enterButton = new JButton("Enter Score");
enterButton.addActionListener(this);

//Top
JPanel topPanel = new JPanel();
topPanel.add(nameLabel);
topPanel.add(nameText);
topPanel.add(scoreLabel);
topPanel.add(scoreText);
topPanel.add(enterButton);
this.add(topPanel, BorderLayout.NORTH);

//Centre
highestLabel = new JLabel("Top scorer is", JLabel.CENTER);
highestLabel.setFont(new Font("Arial", Font.PLAIN, 36));
highestLabel.setForeground(Color.RED);
this.add(highestLabel, BorderLayout.CENTER);

//Bottom
JPanel bottomPanel = new JPanel();
quitButton = new JButton("Quit");
quitButton.addActionListener(this);
bottomPanel.add(quitButton);
this.add(bottomPanel, BorderLayout.SOUTH);

//Use comparator to sort this set
scorerList = new TreeSet<>(new ScoreComparator());
}

/**
* This method execute every time when action happens.
*
* @param e Action event.
*/
@Override
public void actionPerformed(ActionEvent e) {
//If clicked "Enter Score" button
if (e.getSource().equals(enterButton)) {
//If user did not input correct data, popup a message
if (nameText.getText().equals("") || scoreText.getText().equals("")) {
JLabel promptLabel = new JLabel("Please input correct data!", JLabel.CENTER);
JOptionPane.showMessageDialog(null, promptLabel, "Oops!", JOptionPane.ERROR_MESSAGE);
return;
}
try {
int tempScore = Integer.parseInt(scoreText.getText());
//Check if user input correct number
if (tempScore < 0 || tempScore >= 100)
throw new NumberFormatException();

//No problem, create new scorer, and store it
Scorer newScorer = new Scorer(nameText.getText(), tempScore);
scorerList.add(newScorer);

//No need to check if has next
Scorer highestScorer = scorerList.iterator().next();
//Then set the text of high label
highestLabel.setText("Top scorer is " + highestScorer.getName() + " with " + highestScorer.getScore() + "points");
} catch (NumberFormatException ex) { //If user did not input correct number
JLabel promptLabel = new JLabel("Please input correct data!", JLabel.CENTER);
JOptionPane.showMessageDialog(null, promptLabel, "Oops!", JOptionPane.ERROR_MESSAGE);
}
} else if (e.getSource().equals(quitButton)) { //If clicked "Quit" button
//Print all scorer's name and score.
for (Scorer s : scorerList)
System.out.println("Name = " + s.getName() + ", Score = " + s.getScore());
//At last, goodbye my friend!
System.exit(0);
}
}
}
  • Post author: 问少
  • Post link: https://real-neo.me/COM6516.html
  • Copyright Notice: All articles in this blog are licensed under BY-NC-SA unless stating additionally.
0%