initial commit

This commit is contained in:
aj 2019-06-14 12:38:51 +01:00
commit 4380dd04e5
87 changed files with 6542 additions and 0 deletions

58
CS2012 Lab 1/.gitignore vendored Normal file
View File

@ -0,0 +1,58 @@
.metadata
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.settings/
.loadpath
.recommenders
# External tool builders
.externalToolBuilders/
# Locally stored "Eclipse launch configurations"
*.launch
# PyDev specific (Python IDE for Eclipse)
*.pydevproject
# CDT-specific (C/C++ Development Tooling)
.cproject
# CDT- autotools
.autotools
# Java annotation processor (APT)
.factorypath
# PDT-specific (PHP Development Tools)
.buildpath
# sbteclipse plugin
.target
# Tern plugin
.tern-project
# TeXlipse plugin
.texlipse
# STS (Spring Tool Suite)
.springBeans
# Code Recommenders
.recommenders/
# Annotation Processing
.apt_generated/
# Scala IDE specific (Scala & Java development for Eclipse)
.cache-main
.scala_dependencies
.worksheet
.classpath
.project

View File

@ -0,0 +1,97 @@
package doublearray;
import java.util.Scanner;
public class ArrayModifier {
public static void main(String[] args) {
double[] array = getArray();
System.out.print("Original Array: ");
printArray(array);
System.out.println();
System.out.print("Square Root: ");
sqrtArray(array);
System.out.print("Original Array: ");
printArray(array);
System.out.println();
System.out.print("Truncated at 500: ");
truncateArray(array);
printArray(array);
System.out.println();
//double[] newArray = new double[array.length];
double[] newArray = getReciprocalArray(array);
System.out.print("Reciprocal Array: ");
printArray(newArray);
System.out.print("Original Array: ");
printArray(array);
}
static double[] getArray() { //Return array of 10 valid doubles
Scanner scan = new Scanner(System.in);
double[] array = new double[10];
System.out.println("Enter 10 Doubles, 1 per line: ");
for (int counter = 0; counter < 10; counter++) {
while (!scan.hasNextDouble()) {
scan.nextLine();
System.out.println("Error: Enter Double");
}
array[counter] = scan.nextDouble();
}
scan.close();
return array;
}
static void sqrtArray(double[] array) { //Print sqrt of each value
for (double i : array) {
System.out.println(Math.sqrt(i));
}
/*
double[] newArray = new double[array.length];
for (int counter = 0; counter < array.length; counter++) {
newArray[counter] = Math.sqrt(array[counter]);
}
printArray(newArray);
*/
}
static void truncateArray(double[] array) { //truncate values of array to 500
for (int counter = 0; counter < array.length; counter++) {
if (array[counter] > 500)
array[counter] = 500;
}
}
static double[] getReciprocalArray(double[] array) { //returns new array of reciprocals
double[] newArray = new double[array.length];
for (int counter = 0; counter < array.length; counter++) {
newArray[counter] = 1 / array[counter];
}
return newArray;
}
static void printArray(double[] array) { //print out array
System.out.print('{');
for (int counter = 0; counter < array.length; counter++) {
System.out.print(array[counter]);
if (counter != (array.length - 1))
System.out.print(", ");
}
System.out.println('}');
}
}

58
CS2012 Lab 10/.gitignore vendored Normal file
View File

@ -0,0 +1,58 @@
.metadata
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.settings/
.loadpath
.recommenders
# External tool builders
.externalToolBuilders/
# Locally stored "Eclipse launch configurations"
*.launch
# PyDev specific (Python IDE for Eclipse)
*.pydevproject
# CDT-specific (C/C++ Development Tooling)
.cproject
# CDT- autotools
.autotools
# Java annotation processor (APT)
.factorypath
# PDT-specific (PHP Development Tools)
.buildpath
# sbteclipse plugin
.target
# Tern plugin
.tern-project
# TeXlipse plugin
.texlipse
# STS (Spring Tool Suite)
.springBeans
# Code Recommenders
.recommenders/
# Annotation Processing
.apt_generated/
# Scala IDE specific (Scala & Java development for Eclipse)
.cache-main
.scala_dependencies
.worksheet
.classpath
.project

BIN
CS2012 Lab 10/Lab10.jar Executable file

Binary file not shown.

View File

@ -0,0 +1,193 @@
package fx;
import java.io.File;
import java.time.LocalDate;
import java.util.ArrayList;
import io.BinaryMonsterPersister;
import io.MonsterPersister;
import io.TextMonsterPersister;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.DatePicker;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.GridPane;
import javafx.stage.FileChooser;
import model.MonsterAttack;
public class MainController {
private ArrayList<MonsterAttack> list;
public MainController() {
list = new ArrayList<MonsterAttack>();
}
@FXML
private void initialize() {
labelName.getStyleClass().add("headerLabel");
labelLocation.getStyleClass().add("headerLabel");
labelReporter.getStyleClass().add("headerLabel");
labelDate.getStyleClass().add("headerLabel");
refresh();
}
private Label labelName = new Label("monster name");
private Label labelLocation = new Label("location");
private Label labelReporter = new Label("reporter name");
private Label labelDate = new Label("date");
@FXML
private TextField textFieldMonsterName;
@FXML
private TextField textFieldLocation;
@FXML
private TextField textFieldReporter;
@FXML
private DatePicker datePicker;
@FXML
private GridPane gridPane;
@FXML
protected void handleAdd() {
String name = textFieldMonsterName.getText();
String location = textFieldLocation.getText();
String reporter = textFieldReporter.getText();
LocalDate date = datePicker.getValue();
// System.out.println(name + location + reporter + date.toString());
if (name != null && location != null && reporter != null && date != null) {
// System.out.println(date.toString());
MonsterAttack attack = new MonsterAttack(date.toString(), name, location, reporter);
System.out.println(attack);
list.add(attack);
refresh();
}
}
public void refresh() {
gridPane.getChildren().clear();
gridPane.add(labelName, 0, 0);
gridPane.add(labelLocation, 1, 0);
gridPane.add(labelReporter, 2, 0);
gridPane.add(labelDate, 3, 0);
int counter;
for (counter = 0; counter < list.size(); counter++) {
final MonsterAttack attack = list.get(counter);
Label name = new Label(attack.getNameOfMonster());
name.getStyleClass().add("monsterName");
Label location = new Label(attack.getAttackLocation());
Label reporter = new Label(attack.getReporterName());
Label date = new Label(
attack.getMonthOfAttack() + "/" + attack.getDayOfAttack() + "/" + attack.getYearOfAttack());
Button delete = new Button("delete");
delete.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<Event>() {
@Override
public void handle(Event event) {
list.remove(attack);
refresh();
}
});
gridPane.add(name, 0, counter + 1);
gridPane.add(location, 1, counter + 1);
gridPane.add(reporter, 2, counter + 1);
gridPane.add(date, 3, counter + 1);
gridPane.add(delete, 4, counter + 1);
}
}
@FXML
protected void handleSave() {
if (list.size() > 0) {
FileChooser choose = new FileChooser();
choose.setTitle("save attack list");
choose.getExtensionFilters().add(new FileChooser.ExtensionFilter("Text IO", "*.monstertext"));
choose.getExtensionFilters().add(new FileChooser.ExtensionFilter("Binary IO", "*.monsterbinary"));
File file = choose.showSaveDialog(MonsterAttackApplication.getStage());
if (file != null) {
String extension = file.getName().substring(file.getName().lastIndexOf(".") + 1);
System.out.println(extension);
MonsterPersister persist;
if (extension.equals("monstertext")) {
System.out.println("Text");
persist = new TextMonsterPersister();
} else {
System.out.println("Binary");
persist = new BinaryMonsterPersister();
}
persist.write(file, list);
}
}
}
@FXML
protected void handleOpen() {
FileChooser choose = new FileChooser();
choose.setTitle("open attack list");
choose.getExtensionFilters().add(new FileChooser.ExtensionFilter("Text IO", "*.monstertext"));
choose.getExtensionFilters().add(new FileChooser.ExtensionFilter("Binary IO", "*.monsterbinary"));
File file = choose.showOpenDialog(MonsterAttackApplication.getStage());
if (file != null) {
String extension = file.getName().substring(file.getName().lastIndexOf(".") + 1);
// System.out.println(extension);
MonsterPersister persist;
if (extension.equals("monstertext")) {
System.out.println("Text");
persist = new TextMonsterPersister();
} else {
System.out.println("Binary");
persist = new BinaryMonsterPersister();
}
list = persist.read(file);
refresh();
}
}
}

View File

@ -0,0 +1,41 @@
package fx;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class MonsterAttackApplication extends Application {
private static Stage stage;
@Override
public void start(Stage stageIn) throws Exception {
stage = stageIn;
FXMLLoader loader = new FXMLLoader(getClass().getResource("ui/main.fxml"));
Parent root = (Parent)loader.load();
Scene scene = new Scene(root, 1000, 800);
stage.setMinHeight(800);
stage.setMinWidth(960);
stage.setTitle("fm framework");
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
public static Stage getStage() {
return stage;
}
}

View File

@ -0,0 +1,16 @@
.monsterName{
-fx-alignment: center;
-fx-font-size: 150%;
-fx-font-style: italic;
-fx-text-alignment: center;
}
.headerLabel{
-fx-alignment: center;
-fx-font-size: 150%;
-fx-font-weight: bold;
-fx-text-alignment: center;
}

View File

@ -0,0 +1,41 @@
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" stylesheets="@../styles/main.css" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="fx.MainController">
<bottom>
<ToolBar prefHeight="40.0" prefWidth="200.0" BorderPane.alignment="CENTER">
<items>
<TextField fx:id="textFieldMonsterName" promptText="monster name" />
<TextField fx:id="textFieldLocation" promptText="attack location" />
<TextField fx:id="textFieldReporter" promptText="reporter name" />
<DatePicker fx:id="datePicker" promptText="attack date" />
<Button mnemonicParsing="false" onAction="#handleAdd" text="add" />
</items>
</ToolBar>
</bottom>
<top>
<MenuBar BorderPane.alignment="CENTER">
<menus>
<Menu mnemonicParsing="false" text="file">
<items>
<MenuItem fx:id="menuItemSave" mnemonicParsing="false" onAction="#handleSave" text="save" />
<MenuItem fx:id="menuItemOpen" mnemonicParsing="false" onAction="#handleOpen" text="open" />
</items>
</Menu>
</menus>
</MenuBar>
</top>
<center>
<GridPane fx:id="gridPane" BorderPane.alignment="CENTER">
<columnConstraints>
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
</columnConstraints>
</GridPane>
</center>
</BorderPane>

View File

@ -0,0 +1,53 @@
package io;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import model.MonsterAttack;
public class BinaryMonsterPersister implements MonsterPersister{
@Override
public void write(File file, ArrayList<MonsterAttack> list) {
ObjectOutputStream out = null;
try {
out = new ObjectOutputStream(new BufferedOutputStream(
new FileOutputStream(file)));
out.writeObject(list);
out.close();
}catch(Exception e) {
e.printStackTrace();
}
}
@Override
public ArrayList<MonsterAttack> read(File file) {
ObjectInputStream in = null;
ArrayList<MonsterAttack> list = null;
try {
in = new ObjectInputStream(new BufferedInputStream(
new FileInputStream(file)));
list = (ArrayList<MonsterAttack>) in.readObject();
in.close();
}catch(Exception e) {
e.printStackTrace();
}
return list;
}
}

View File

@ -0,0 +1,14 @@
package io;
import java.io.File;
import java.util.ArrayList;
import model.MonsterAttack;
public interface MonsterPersister {
public void write(File file, ArrayList<MonsterAttack> list);
public ArrayList<MonsterAttack> read(File file);
}

View File

@ -0,0 +1,79 @@
package io;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
import model.MonsterAttack;
public class TextMonsterPersister implements MonsterPersister{
@Override
public void write(File file, ArrayList<MonsterAttack> list) {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
int counter;
MonsterAttack attack;
for(counter = 0; counter < list.size(); counter++) {
attack = list.get(counter);
writer.write(attack.getAttackId() + "," +
attack.getYearOfAttack() + "-" +
attack.getMonthOfAttack() + "-" +
attack.getDayOfAttack() + "," +
attack.getNameOfMonster() + "," +
attack.getAttackLocation() + "," +
attack.getReporterName());
if(counter != (list.size() - 1)) writer.newLine();
}
writer.close();
System.out.println("File Written Successfully");
}
catch(IOException e){
System.out.println(" ERROR: " + e);
System.out.println("File Writing Aborted");
}
}
@Override
public ArrayList<MonsterAttack> read(File file) {
ArrayList<MonsterAttack> list = new ArrayList<MonsterAttack>();
try {
Scanner fscan = new Scanner(file);
String attackLine = null;
String[] attackData = null;
int attackId;
while(fscan.hasNextLine()) {
attackLine = fscan.nextLine();
attackData = attackLine.split(",");
attackId = Integer.parseInt(attackData[0]);
MonsterAttack attack = new MonsterAttack(attackData[1], attackData[2], attackData[3], attackData[4]);
attack.setAttackId(attackId);
list.add(attack);
}
fscan.close();
}catch(IOException e) {
System.out.println(" ERROR: " + e);
}catch(NumberFormatException e) {
System.out.println(" ERROR: Invalid File " + e);
}catch(ArrayIndexOutOfBoundsException e) {
System.out.println(" ERROR: Not Enough Data For Attack Found (5 Columns Expected) " + e);
}
return list;
}
}

View File

@ -0,0 +1,116 @@
package model;
import java.io.Serializable;
public class MonsterAttack implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private int attackId;
private int dayOfAttack;
private int monthOfAttack;
private int yearOfAttack;
private String nameOfMonster;
private String attackLocation;
private String reporterName;
private static int lastAttackId = 0;
public MonsterAttack(String argDate, String argMonsterName, String argLocation, String argReporter) {
lastAttackId += 1;
this.setNameOfMonster(argMonsterName);
this.setAttackLocation(argLocation);
this.setReporterName(argReporter);
this.setAttackId(lastAttackId);
String[] arrOfDate = argDate.split("-", 4);
try {
if (arrOfDate.length == 3) {
this.setDayOfAttack(Integer.parseInt(arrOfDate[2]));
this.setMonthOfAttack(Integer.parseInt(arrOfDate[1]));
this.setYearOfAttack(Integer.parseInt(arrOfDate[0]));
}
} catch (Exception e) {
System.out.println(" ERROR: " + e);
System.out.println(" Error Setting Date, Default to 0/0/0");
}
}
public int getAttackId() {
return attackId;
}
public void setAttackId(int attackId) {
this.attackId = attackId;
}
public int getDayOfAttack() {
return dayOfAttack;
}
public void setDayOfAttack(int dayOfAttack) {
this.dayOfAttack = dayOfAttack;
}
public int getMonthOfAttack() {
return monthOfAttack;
}
public void setMonthOfAttack(int monthOfAttack) {
this.monthOfAttack = monthOfAttack;
}
public int getYearOfAttack() {
return yearOfAttack;
}
public void setYearOfAttack(int yearOfAttack) {
this.yearOfAttack = yearOfAttack;
}
public String getNameOfMonster() {
return nameOfMonster;
}
public void setNameOfMonster(String nameOfMonster) {
this.nameOfMonster = nameOfMonster;
}
public String getAttackLocation() {
return attackLocation;
}
public void setAttackLocation(String attackLocation) {
this.attackLocation = attackLocation;
}
public String getReporterName() {
return reporterName;
}
public void setReporterName(String reporterName) {
this.reporterName = reporterName;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(this.getAttackId());
sb.append("#: ");
sb.append(this.getNameOfMonster());
sb.append(" at ");
sb.append(this.getAttackLocation());
sb.append(" on ");
sb.append(this.getMonthOfAttack());
sb.append("/");
sb.append(this.getDayOfAttack());
sb.append("/");
sb.append(this.getYearOfAttack());
sb.append(", Reported By ");
sb.append(this.getReporterName());
String str = sb.toString();
return str;
}
}

58
CS2012 Lab 11/.gitignore vendored Normal file
View File

@ -0,0 +1,58 @@
.metadata
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.settings/
.loadpath
.recommenders
# External tool builders
.externalToolBuilders/
# Locally stored "Eclipse launch configurations"
*.launch
# PyDev specific (Python IDE for Eclipse)
*.pydevproject
# CDT-specific (C/C++ Development Tooling)
.cproject
# CDT- autotools
.autotools
# Java annotation processor (APT)
.factorypath
# PDT-specific (PHP Development Tools)
.buildpath
# sbteclipse plugin
.target
# Tern plugin
.tern-project
# TeXlipse plugin
.texlipse
# STS (Spring Tool Suite)
.springBeans
# Code Recommenders
.recommenders/
# Annotation Processing
.apt_generated/
# Scala IDE specific (Scala & Java development for Eclipse)
.cache-main
.scala_dependencies
.worksheet
.classpath
.project

View File

@ -0,0 +1,84 @@
import java.util.List;
public class Recursion {
public boolean checkPrime(int testNumber) {
boolean isPrime = checkPrimeRecursive(testNumber, 2);
System.out.println(testNumber + " isPrime: " + isPrime);
return isPrime;
}
private boolean checkPrimeRecursive(int testNumber, int factor) {
if (testNumber < 2) {
return false;
}
if (testNumber == 2) {
return true;
}
if (testNumber == 9) {
return false;
}
int remainder = testNumber % factor;
if (remainder == 0) {
// System.out.println(testNumber + " completely divisible, not prime");
return false;
} else {
// if(((double)factor > (double)testNumber / (double) 5)) {
// if (factor > (testNumber / 5) && testNumber > 10) {
// if (factor > testNumber / 5 && !(testNumber > 10)) {
// if (testNumber > factor / 5) {
if (factor > testNumber / 5) {
return true;
} else {
return checkPrimeRecursive(testNumber, factor + 1);
}
}
// return true;
}
public int sumOfList(List<Integer> numbers) {
if (numbers == null || numbers.size() == 0) {
return 0;
}
if (numbers.size() == 1) {
return numbers.get(0);
} else {
int current = numbers.get(0);
// List<Integer> newList = numbers;
// newList.remove(0);
//
// return current + sumOfList(newList);
numbers.remove(0);
return current + sumOfList(numbers);
}
}
}

View File

@ -0,0 +1,276 @@
import static org.junit.jupiter.api.Assertions.*;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
class RecursionTest {
@Test
void testPrimeNegNumber() {
Recursion recursion = new Recursion();
assertFalse(recursion.checkPrime(-4));
}
@Test
void testPrime0() {
Recursion recursion = new Recursion();
assertFalse(recursion.checkPrime(0));
}
@Test
void testPrime1() {
Recursion recursion = new Recursion();
assertFalse(recursion.checkPrime(1));
}
@Test
void testPrime2() {
Recursion recursion = new Recursion();
assertTrue(recursion.checkPrime(2));
}
@Test
void testPrime3() {
Recursion recursion = new Recursion();
assertTrue(recursion.checkPrime(3));
}
@Test
void testPrime4() {
Recursion recursion = new Recursion();
assertFalse(recursion.checkPrime(4));
}
@Test
void testPrime5() {
Recursion recursion = new Recursion();
assertTrue(recursion.checkPrime(5));
}
@Test
void testPrime6() {
Recursion recursion = new Recursion();
assertFalse(recursion.checkPrime(6));
}
@Test
void testPrime7() {
Recursion recursion = new Recursion();
assertTrue(recursion.checkPrime(7));
}
@Test
void testPrime8() {
Recursion recursion = new Recursion();
assertFalse(recursion.checkPrime(8));
}
@Test
void testPrime9() {
Recursion recursion = new Recursion();
// System.out.println(recursion.checkPrime(9));
assertFalse(recursion.checkPrime(9));
}
@Test
void testPrime10() {
Recursion recursion = new Recursion();
assertFalse(recursion.checkPrime(10));
}
@Test
void testPrime11() {
Recursion recursion = new Recursion();
assertTrue(recursion.checkPrime(11));
}
@Test
void testPrime12() {
Recursion recursion = new Recursion();
assertFalse(recursion.checkPrime(12));
}
@Test
void testPrime13() {
Recursion recursion = new Recursion();
assertTrue(recursion.checkPrime(13));
}
@Test
void testPrime17() {
Recursion recursion = new Recursion();
assertTrue(recursion.checkPrime(17));
}
@Test
void testPrime19() {
Recursion recursion = new Recursion();
assertTrue(recursion.checkPrime(19));
}
@Test
void testPrime21() {
Recursion recursion = new Recursion();
assertFalse(recursion.checkPrime(21));
}
@Test
void testPrime23() {
Recursion recursion = new Recursion();
assertTrue(recursion.checkPrime(23));
}
@Test
void testPrime29() {
Recursion recursion = new Recursion();
assertTrue(recursion.checkPrime(29));
}
@Test
void testPrime30() {
Recursion recursion = new Recursion();
assertFalse(recursion.checkPrime(30));
}
@Test
void testPrime99() {
Recursion recursion = new Recursion();
assertFalse(recursion.checkPrime(99));
}
@Test
void testSumNullList() {
Recursion recursion = new Recursion();
List<Integer> list = null;
int sum = recursion.sumOfList(list);
assertEquals(sum, 0);
}
@Test
void testSumEmpty() {
Recursion recursion = new Recursion();
List<Integer> list = new ArrayList<Integer>();
int sum = recursion.sumOfList(list);
assertEquals(sum, 0);
}
@Test
void testSumSingularItem() {
Recursion recursion = new Recursion();
List<Integer> list = new ArrayList<Integer>();
list.add(5);
int sum = recursion.sumOfList(list);
assertEquals(sum, 5);
}
@Test
void testSumList() {
Recursion recursion = new Recursion();
List<Integer> list = new ArrayList<Integer>();
int counter;
for(counter = 0; counter < 5; counter++) {
list.add(counter + 1);
}
int sum = recursion.sumOfList(list);
assertEquals(sum, 15);
}
@Test
void testSumList2() {
Recursion recursion = new Recursion();
List<Integer> list = new ArrayList<Integer>();
int counter;
for(counter = 0; counter < 2; counter++) {
list.add(counter + 1);
}
int sum = recursion.sumOfList(list);
assertEquals(sum, 3);
}
@Test
void testSumList3() {
Recursion recursion = new Recursion();
List<Integer> list = new ArrayList<Integer>();
list.add(2);
list.add(2);
list.add(3);
int sum = recursion.sumOfList(list);
assertEquals(sum, 7);
}
@Test
void testSumListWithNegative() {
Recursion recursion = new Recursion();
List<Integer> list = new ArrayList<Integer>();
list.add(2);
list.add(2);
list.add(-3);
int sum = recursion.sumOfList(list);
assertEquals(sum, 1);
}
@Test
void testSumListNegativeAnswer() {
Recursion recursion = new Recursion();
List<Integer> list = new ArrayList<Integer>();
list.add(2);
list.add(2);
list.add(-3);
list.add(-3);
int sum = recursion.sumOfList(list);
assertEquals(sum, -2);
}
}

58
CS2012 Lab 2 redux/.gitignore vendored Normal file
View File

@ -0,0 +1,58 @@
.metadata
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.settings/
.loadpath
.recommenders
# External tool builders
.externalToolBuilders/
# Locally stored "Eclipse launch configurations"
*.launch
# PyDev specific (Python IDE for Eclipse)
*.pydevproject
# CDT-specific (C/C++ Development Tooling)
.cproject
# CDT- autotools
.autotools
# Java annotation processor (APT)
.factorypath
# PDT-specific (PHP Development Tools)
.buildpath
# sbteclipse plugin
.target
# Tern plugin
.tern-project
# TeXlipse plugin
.texlipse
# STS (Spring Tool Suite)
.springBeans
# Code Recommenders
.recommenders/
# Annotation Processing
.apt_generated/
# Scala IDE specific (Scala & Java development for Eclipse)
.cache-main
.scala_dependencies
.worksheet
.classpath
.project

View File

@ -0,0 +1,102 @@
package doublearraylist;
import java.util.ArrayList;
import java.util.Scanner;
public class ArrayListModifier {
public static void main(String[] args) {
ArrayList<Double> array = getArray();
System.out.print("Original Array: ");
printArray(array);
System.out.println();
System.out.print("Square Root: ");
sqrtArray(array);
System.out.print("Original Array: ");
printArray(array);
System.out.println();
System.out.print("Truncated at 500: ");
truncateArray(array);
printArray(array);
System.out.println();
// double[] newArray = new double[array.length];
ArrayList<Double> newArray = getReciprocalArray(array);
System.out.print("Reciprocal Array: ");
printArray(newArray);
System.out.print("Original Array: ");
printArray(array);
}
static ArrayList<Double> getArray() { // Return array of 10 valid doubles
Scanner scan = new Scanner(System.in);
ArrayList<Double> array = new ArrayList<Double>();
int arraysize;
System.out.println("How many Doubles would you like?: ");
while (!scan.hasNextInt()) {
scan.nextLine();
System.out.println("Error: Enter Int");
}
arraysize = scan.nextInt();
System.out.println("Enter " + arraysize + " Doubles, 1 per line: ");
for (int counter = 0; counter < arraysize; counter++) {
while (!scan.hasNextDouble()) {
scan.nextLine();
System.out.println("Error: Enter Double");
}
array.add(scan.nextDouble());
}
scan.close();
return array;
}
static void sqrtArray(ArrayList<Double> array) { // Print sqrt of each value
for (double i : array) {
System.out.println(Math.sqrt(i));
}
/*
* double[] newArray = new double[array.length]; for (int counter = 0; counter <
* array.length; counter++) {
*
* newArray[counter] = Math.sqrt(array[counter]); } printArray(newArray);
*/
}
static void truncateArray(ArrayList<Double> array) { // truncate values of array to 500
for (int counter = 0; counter < array.size(); counter++) {
if (array.get(counter) > 500)
array.set(counter, (double)500);
}
}
static ArrayList<Double> getReciprocalArray(ArrayList<Double> array) { // returns new array of reciprocals
ArrayList<Double> newArray = new ArrayList<Double>();
for (int counter = 0; counter < array.size(); counter++) {
newArray.add(1/array.get(counter));
}
return newArray;
}
static void printArray(ArrayList<Double> array) { // print out array
System.out.print('{');
for (int counter = 0; counter < array.size(); counter++) {
System.out.print(array.get(counter));
if (counter != (array.size() - 1))
System.out.print(", ");
}
System.out.println('}');
}
}

58
CS2012 Lab 3/.gitignore vendored Normal file
View File

@ -0,0 +1,58 @@
.metadata
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.settings/
.loadpath
.recommenders
# External tool builders
.externalToolBuilders/
# Locally stored "Eclipse launch configurations"
*.launch
# PyDev specific (Python IDE for Eclipse)
*.pydevproject
# CDT-specific (C/C++ Development Tooling)
.cproject
# CDT- autotools
.autotools
# Java annotation processor (APT)
.factorypath
# PDT-specific (PHP Development Tools)
.buildpath
# sbteclipse plugin
.target
# Tern plugin
.tern-project
# TeXlipse plugin
.texlipse
# STS (Spring Tool Suite)
.springBeans
# Code Recommenders
.recommenders/
# Annotation Processing
.apt_generated/
# Scala IDE specific (Scala & Java development for Eclipse)
.cache-main
.scala_dependencies
.worksheet
.classpath
.project

View File

@ -0,0 +1,121 @@
package monsterattack;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class AttackMonitor {
private List<MonsterAttack> attacks = new ArrayList<MonsterAttack>();
private Scanner scan = new Scanner(System.in);
public void monitor() {
int menuChoice = 0;
do {
System.out.println("-------------------");
System.out.println("0: quit");
System.out.println("1: add monster");
System.out.println("2: view monsters");
System.out.println("3: delete monster");
System.out.print("Enter Option: ");
while (!scan.hasNextInt()) {
scan.nextLine();
System.out.println("-------------------");
System.out.println(" ERROR: Enter Int");
System.out.println("-------------------");
System.out.print("Enter Option: ");
}
menuChoice = scan.nextInt();
switch (menuChoice) {
case 0:
break;
case 1:
addMonster();
break;
case 2:
showMonsters();
break;
case 3:
deleteMonster();
break;
}
} while (menuChoice != 0);
}
public void insertMonster(String dateOfAttack, String nameOfMonster, String locationOfAttack, String nameOfReporter) {
MonsterAttack monster = new MonsterAttack(dateOfAttack, nameOfMonster, locationOfAttack, nameOfReporter);
attacks.add(monster);
}
private void addMonster() {
System.out.println("-------------------");
System.out.print("Enter Name Of Monster: ");
String nameOfMonster = scan.next();
String dateOfAttack = null;
do {
System.out.print("Enter Date of Attack (MM/DD/YYYY): ");
dateOfAttack = scan.next();
if(dateOfAttack.length() > 10) {
dateOfAttack = null;
System.out.println(" ERROR: String too long");
}
}while(dateOfAttack == null);
System.out.print("Enter Location Of Attack: ");
String locationOfAttack = scan.next();
System.out.print("Enter Name Of Reporter: ");
String nameOfReporter = scan.next();
attacks.add(new MonsterAttack(dateOfAttack, nameOfMonster, locationOfAttack, nameOfReporter));
}
private void showMonsters() {
System.out.println("-------------------");
if (attacks.size() != 0) {
for (int i = 0; i < attacks.size(); i++) {
// System.out.print('\t');
System.out.println(attacks.get(i));
}
} else {
System.out.println(" ERROR: List Empty");
}
}
private void deleteMonster() {
showMonsters();
System.out.println("-------------------");
System.out.print("Enter ID of Attack from list above: ");
while (!scan.hasNextInt()) {
scan.nextLine();
System.out.println("ERROR: Enter Int");
}
int idToDelete = scan.nextInt();
boolean found = false;
for (int counter = 0; counter < attacks.size(); counter++) {
int attackId = attacks.get(counter).getAttackId();
if (attackId == idToDelete) {
found = true;
attacks.remove(counter);
// break;
}
// counter++;
}
if (found == false)
System.out.println("-------------------\nAttack of given ID not found");
}
}

View File

@ -0,0 +1,110 @@
package monsterattack;
public class MonsterAttack {
private int attackId;
private int dayOfAttack;
private int monthOfAttack;
private int yearOfAttack;
private String nameOfMonster;
private String attackLocation;
private String reporterName;
private static int lastAttackId = 0;
public MonsterAttack(String argDate, String argMonsterName, String argLocation, String argReporter) {
lastAttackId += 1;
this.setNameOfMonster(argMonsterName);
this.setAttackLocation(argLocation);
this.setReporterName(argReporter);
this.setAttackId(lastAttackId);
String[] arrOfDate = argDate.split("/", 4);
try {
if (arrOfDate.length == 3) {
this.setDayOfAttack(Integer.parseInt(arrOfDate[1]));
this.setMonthOfAttack(Integer.parseInt(arrOfDate[0]));
this.setYearOfAttack(Integer.parseInt(arrOfDate[2]));
}
} catch (Exception e) {
System.out.println(" ERROR: " + e);
System.out.println(" Error Setting Date, Default to 0/0/0");
}
}
public int getAttackId() {
return attackId;
}
public void setAttackId(int attackId) {
this.attackId = attackId;
}
public int getDayOfAttack() {
return dayOfAttack;
}
public void setDayOfAttack(int dayOfAttack) {
this.dayOfAttack = dayOfAttack;
}
public int getMonthOfAttack() {
return monthOfAttack;
}
public void setMonthOfAttack(int monthOfAttack) {
this.monthOfAttack = monthOfAttack;
}
public int getYearOfAttack() {
return yearOfAttack;
}
public void setYearOfAttack(int yearOfAttack) {
this.yearOfAttack = yearOfAttack;
}
public String getNameOfMonster() {
return nameOfMonster;
}
public void setNameOfMonster(String nameOfMonster) {
this.nameOfMonster = nameOfMonster;
}
public String getAttackLocation() {
return attackLocation;
}
public void setAttackLocation(String attackLocation) {
this.attackLocation = attackLocation;
}
public String getReporterName() {
return reporterName;
}
public void setReporterName(String reporterName) {
this.reporterName = reporterName;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(this.getAttackId());
sb.append("#: ");
sb.append(this.getNameOfMonster());
sb.append(" at ");
sb.append(this.getAttackLocation());
sb.append(" on ");
sb.append(this.getMonthOfAttack());
sb.append("/");
sb.append(this.getDayOfAttack());
sb.append("/");
sb.append(this.getYearOfAttack());
sb.append(", Reported By ");
sb.append(this.getReporterName());
String str = sb.toString();
return str;
}
}

View File

@ -0,0 +1,19 @@
package monsterattack;
public class MonsterAttackDriver {
public static void main(String[] args) {
AttackMonitor monitor = new AttackMonitor();
hardcodeAttacks(monitor);
monitor.monitor();
}
public static void hardcodeAttacks(AttackMonitor monitor) {
monitor.insertMonster("05/22/1980", "Godzilla1", "London", "Bill");
monitor.insertMonster("06/4/2005", "Godzilla2", "Paris", "Jeff");
monitor.insertMonster("07/6/1998", "Godzilla3", "Dublin", "Andy");
}
}

58
CS2012 Lab 4/.gitignore vendored Normal file
View File

@ -0,0 +1,58 @@
.metadata
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.settings/
.loadpath
.recommenders
# External tool builders
.externalToolBuilders/
# Locally stored "Eclipse launch configurations"
*.launch
# PyDev specific (Python IDE for Eclipse)
*.pydevproject
# CDT-specific (C/C++ Development Tooling)
.cproject
# CDT- autotools
.autotools
# Java annotation processor (APT)
.factorypath
# PDT-specific (PHP Development Tools)
.buildpath
# sbteclipse plugin
.target
# Tern plugin
.tern-project
# TeXlipse plugin
.texlipse
# STS (Spring Tool Suite)
.springBeans
# Code Recommenders
.recommenders/
# Annotation Processing
.apt_generated/
# Scala IDE specific (Scala & Java development for Eclipse)
.cache-main
.scala_dependencies
.worksheet
.classpath
.project

View File

@ -0,0 +1,53 @@
package universitymanager;
public class Address {
private int streetNumber;
private String streetName;
private String cityName;
private String stateName;
private String countryName;
public Address(int streetNumber, String streetName, String cityName, String stateName, String countryName) {
this.streetNumber = streetNumber;
this.streetName = streetName;
this.cityName = cityName;
this.stateName = stateName;
this.countryName = countryName;
}
public String toString() {
return streetNumber + " " + streetName + "\n" + cityName + "\n" + stateName + "\n" + countryName;
}
public int getStreetNumber() {
return streetNumber;
}
public void setStreetNumber(int streetNumber) {
this.streetNumber = streetNumber;
}
public String getStreetName() {
return streetName;
}
public void setStreetName(String streetName) {
this.streetName = streetName;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public String getStateName() {
return stateName;
}
public void setStateName(String stateName) {
this.stateName = stateName;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
}

View File

@ -0,0 +1,31 @@
package universitymanager;
public class Course {
private String courseIdentifier;
private int numberOfUnits;
public Course(String courseIdentifier, int numberOfUnits) {
this.courseIdentifier = courseIdentifier;
this.numberOfUnits = numberOfUnits;
}
public String toString() {
return courseIdentifier + ": " + numberOfUnits + " Units";
}
public String getCourseIdentifier() {
return courseIdentifier;
}
public void setCourseIdentifier(String courseIdentifier) {
this.courseIdentifier = courseIdentifier;
}
public int getNumberOfUnits() {
return numberOfUnits;
}
public void setNumberOfUnits(int numberOfUnits) {
this.numberOfUnits = numberOfUnits;
}
}

View File

@ -0,0 +1,28 @@
package universitymanager;
public class Driver {
public static void main(String[] args) {
University uni = new University();
uni.insertStudent("Andy", 149, "Test", "Amersham", "Bucks", "UK", 34);
uni.insertStudent("Bob", 149, "Test Road", "Amersham", "Bucks", "UK", 35);
uni.insertStudent("Carl", 149, "Test Road", "Amersham", "Bucks", "UK", 36);
uni.insertStudent("Derek", 149, "Test Road", "Amersham", "Bucks", "UK", 37);
uni.insertStudent("Evan", 149, "Test Road", "Amersham", "Bucks", "UK", 38);
uni.insertStudent("Fred", 149, "Test Road", "Amersham", "Bucks", "UK", 39);
uni.insertStudent("George", 149, "Test Road", "Amersham", "Bucks", "UK", 41);
uni.insertFaculty("Harry", 149, "Test Road", "Amersham", "Bucks", "UK", 40);
uni.insertFaculty("Ivan", 149, "Test Road", "Amersham", "Bucks", "UK", 45);
uni.insertFaculty("Jerry", 149, "Test Road", "Amersham", "Bucks", "UK", 48);
uni.insertFaculty("Kevin", 149, "Test Road", "Amersham", "Bucks", "UK", 80);
uni.insertFaculty("Liam", 149, "Test Road", "Amersham", "Bucks", "UK", 90);
uni.insertCourse("EE-324", 4);
uni.insertCourse("CS-2352", 8);
uni.insertCourse("PH-342", 8);
uni.insertCourse("EN-754", 8);
uni.menu();
}
}

View File

@ -0,0 +1,23 @@
package universitymanager;
public class FacultyMember extends Person{
private int employeeId;
public FacultyMember(String name, Address address, int employeeId) {
super(name, address);
this.employeeId = employeeId;
}
public String toString() {
return employeeId + "#: " + name;
}
public int getEmployeeId() {
return employeeId;
}
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
}

View File

@ -0,0 +1,54 @@
package universitymanager;
import java.util.ArrayList;
public class Person {
protected String name;
protected Address address;
private ArrayList<Course> courseSchedule = new ArrayList<Course>();
public Person(String name, Address address) {
this.name = name;
this.address = address;
}
public String toString() {
return name;
}
public void enrollCourse(Course course) {
courseSchedule.add(course);
}
public int getNumberOfCourses() {
return courseSchedule.size();
}
public void dropCourse(Course course) {
courseSchedule.remove(course);
}
public String getCourseIdentifier(int index) {
return courseSchedule.get(index).getCourseIdentifier();
}
public ArrayList<Course> getCourses() {
return courseSchedule;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}

View File

@ -0,0 +1,23 @@
package universitymanager;
public class Student extends Person{
private int CIN;
public Student(String name, Address address, int CIN){
super(name, address);
this.CIN = CIN;
}
public String toString() {
return CIN + "#: " + name;
}
public int getCIN() {
return CIN;
}
public void setCIN(int cIN) {
CIN = cIN;
}
}

View File

@ -0,0 +1,479 @@
package universitymanager;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class University {
private ArrayList<Student> students = new ArrayList<Student>();
private ArrayList<FacultyMember> faculty = new ArrayList<FacultyMember>();
private ArrayList<Course> courses = new ArrayList<Course>();
public void menu() {
int response = 0;
do {
String[] menuChoices = { "Exit", "Student", "Faculty", "Course" };
response = JOptionPane.showOptionDialog(null, "Select Object Manager:", "University Manager",
JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, menuChoices, menuChoices[0]);
switch (response) {
case 0:
break;
case 1:
studentMenu();
break;
case 2:
facultyMenu();
break;
case 3:
courseMenu();
break;
}
} while (response != 0);
}
private void studentMenu() {
String[] menuChoices = { "Back", "Add Student", "Delete Student", "View Students", "Manage Student's Courses" };
int response = JOptionPane.showOptionDialog(null, "Student Menu\n" + students.size() + " Students Registered", "Student Manager", JOptionPane.DEFAULT_OPTION,
JOptionPane.INFORMATION_MESSAGE, null, menuChoices, menuChoices[0]);
switch (response) {
case 0:
break;
case 1:
addStudent();
break;
case 2:
deleteStudent();
break;
case 3:
viewStudents();
break;
case 4:
manageStudentCourses();
break;
}
}
private void facultyMenu() {
String[] menuChoices = { "Back", "Add Faculty", "Delete Faculty", "View Faculty", "Manage Teaching Schedule" };
int response = JOptionPane.showOptionDialog(null, "Faculty Menu\n" + faculty.size() + " Employees Registered", "Faculty Manager", JOptionPane.DEFAULT_OPTION,
JOptionPane.INFORMATION_MESSAGE, null, menuChoices, menuChoices[0]);
switch (response) {
case 0:
break;
case 1:
addFaculty();
break;
case 2:
deleteFaculty();
break;
case 3:
viewFaculty();
break;
case 4:
manageFacultyCourses();
break;
}
}
private void courseMenu() {
String[] menuChoices = { "Back", "Add Course", "View Courses" };
int response = JOptionPane.showOptionDialog(null, "Course Menu\n" + courses.size() + " Registered", "Course Manager", JOptionPane.DEFAULT_OPTION,
JOptionPane.INFORMATION_MESSAGE, null, menuChoices, menuChoices[0]);
switch (response) {
case 0:
break;
case 1:
addCourse();
break;
case 2:
viewCourses();
break;
}
}
// VIEW LIST METHODS
private void viewStudents() {
if (students.size() > 0) {
int counter;
StringBuilder sb = new StringBuilder();
for (counter = 0; counter < students.size(); counter++) {
sb.append(students.get(counter) + " - " + students.get(counter).getNumberOfCourses() + " Course(s)");
sb.append("\n");
}
JOptionPane.showMessageDialog(null, sb, "Student List", JOptionPane.DEFAULT_OPTION, null);
}else {
JOptionPane.showMessageDialog(null, "No Students Registered", "Error: Empty List", JOptionPane.ERROR_MESSAGE);
}
}
private void viewFaculty() {
if (faculty.size() > 0) {
int counter;
StringBuilder sb = new StringBuilder();
for (counter = 0; counter < faculty.size(); counter++) {
sb.append(faculty.get(counter) + " - " + faculty.get(counter).getNumberOfCourses() + " Course(s)");
sb.append("\n");
}
JOptionPane.showMessageDialog(null, sb, "Faculty List", JOptionPane.DEFAULT_OPTION, null);
}else {
JOptionPane.showMessageDialog(null, "No Faculty Registered", "Error: Empty List", JOptionPane.ERROR_MESSAGE);
}
}
private void viewCourses() {
if (courses.size() > 0) {
int counter;
StringBuilder sb = new StringBuilder();
for (counter = 0; counter < courses.size(); counter++) {
sb.append(courses.get(counter));
sb.append("\n");
}
JOptionPane.showMessageDialog(null, sb, "Course List", JOptionPane.DEFAULT_OPTION, null);
}else {
JOptionPane.showMessageDialog(null, "No Courses Registered", "Error: List Empty", JOptionPane.ERROR_MESSAGE);
}
}
// COURSE MANAGEMENT METHODS
private void manageStudentCourses() {
//GET STUDENT FROM USER
Object[] options = students.toArray();
Object choice = JOptionPane.showInputDialog(null, "Pick a Student to Manage", "Student Course Manager",
JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
int index = students.indexOf(choice);
if (index != -1) {
//PRINT STUDENT INFORMATION
StringBuilder sb = new StringBuilder();
Student student = students.get(index);
String message = student.getName() + "\n#" + student.getCIN() + "\n" + student.getAddress();
sb.append(message);
if (student.getNumberOfCourses() > 0) {
//PRINT COURSES
sb.append("\n\n");
int i;
for (i = 0; i < student.getNumberOfCourses(); i++) {
sb.append(student.getCourseIdentifier(i));
sb.append("\n");
}
// SHOW MENU WITH DROP BUTTON
String[] menuChoices = { "Add Course", "Remove Course", "Back" };
int menuChoice = JOptionPane.showOptionDialog(null, sb, student.getName() + " - " + student.getCIN(),
JOptionPane.DEFAULT_OPTION, JOptionPane.DEFAULT_OPTION, null, menuChoices, menuChoices[0]);
switch (menuChoice) {
case 0:
enrollCourse(students.get(index));
break;
case 1:
dropCourse(students.get(index));
break;
case 2:
break;
}
} else {
// SHOW MENU NO DROP BUTTON
sb.append("\n\nNo Courses Enrolled");
String[] menuChoices = { "Add Course", "Back" };
int menuChoice = JOptionPane.showOptionDialog(null, sb, student.getName() + " - " + student.getCIN(),
JOptionPane.DEFAULT_OPTION, JOptionPane.DEFAULT_OPTION, null, menuChoices, menuChoices[0]);
switch (menuChoice) {
case 0:
enrollCourse(students.get(index));
break;
case 1:
break;
}
}
}
}
private void manageFacultyCourses() {
//GET FACULTY MEMBER FROM USER
Object[] options = faculty.toArray();
Object choice = JOptionPane.showInputDialog(null, "Pick a Faculty Member to Manage", "Faculty Course Manager",
JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
int index = faculty.indexOf(choice);
if (index != -1) {
//PRINT FACULTY INFORMATION
StringBuilder sb = new StringBuilder();
FacultyMember facultymember = faculty.get(index);
String message = facultymember.getName() + "\n#" + facultymember.getEmployeeId() + "\n"
+ facultymember.getAddress();
sb.append(message);
if (facultymember.getNumberOfCourses() > 0) {
//PRINT COURSES
sb.append("\n\n");
int i;
for (i = 0; i < facultymember.getNumberOfCourses(); i++) {
sb.append(facultymember.getCourseIdentifier(i));
sb.append("\n");
}
// SHOW MENU WITH DROP BUTTON
String[] menuChoices = { "Add Course", "Remove Course", "Back" };
int menuChoice = JOptionPane.showOptionDialog(null, sb,
facultymember.getName() + " - " + facultymember.getEmployeeId(), JOptionPane.DEFAULT_OPTION,
JOptionPane.DEFAULT_OPTION, null, menuChoices, menuChoices[0]);
switch (menuChoice) {
case 0:
enrollCourse(faculty.get(index));
break;
case 1:
dropCourse(faculty.get(index));
break;
case 2:
break;
}
} else {
// SHOW MENU NO DROP BUTTON
sb.append("\n\nNo Courses Enrolled");
String[] menuChoices = { "Add Course", "Back" };
int menuChoice = JOptionPane.showOptionDialog(null, sb,
facultymember.getName() + " - " + facultymember.getEmployeeId(), JOptionPane.DEFAULT_OPTION,
JOptionPane.DEFAULT_OPTION, null, menuChoices, menuChoices[0]);
switch (menuChoice) {
case 0:
enrollCourse(faculty.get(index));
break;
case 1:
break;
}
}
}
}
private void enrollCourse(Person person) {
//CREATE MENU OPTIONS FROM REGISTERED COURSES
ArrayList<Course> menuOptions = new ArrayList<Course>();
int counter;
for(counter = 0; counter < courses.size(); counter++) {
Course course = courses.get(counter);
menuOptions.add(course);
}
//REMOVE ALREADY ENROLLED COURSES FROM OPTIONS
ArrayList<Course> courseSchedule = person.getCourses();
for(counter = 0; counter < courseSchedule.size(); counter++) {
menuOptions.remove(courseSchedule.get(counter));
}
Object[] options = menuOptions.toArray();
if(options.length != 0) {
Object choice = JOptionPane.showInputDialog(null, "Pick a Course to Enroll in", "Add a Course",
JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
if(choice != null) {
int index = courses.indexOf(choice);
Course course = courses.get(index);
person.enrollCourse(course);
}
}else {
JOptionPane.showMessageDialog(null, "No Courses Left to Enroll", "Error: No Courses", JOptionPane.ERROR_MESSAGE);
}
}
private void dropCourse(Person person) {
Object[] options = person.getCourses().toArray();
Object choice = JOptionPane.showInputDialog(null, "Pick a Course to Drop", "Drop a Course",
JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
if(choice != null) {
int index = courses.indexOf(choice);
Course course = courses.get(index);
person.dropCourse(course);
}
}
// ADD METHODS
public void addStudent() {
String name = JOptionPane.showInputDialog(null, "Enter Student Name:");
if(name != null && name.length() > 0) {
int idNumber = -1;
String idNumberString = JOptionPane.showInputDialog(null, "Enter Student CIN:");
if(idNumberString != null) {
try{
idNumber = Integer.parseInt(idNumberString);
}catch(NumberFormatException e) {
idNumber = -1;
JOptionPane.showMessageDialog(null, "CIN Must be Number", "Error: Int Required", JOptionPane.ERROR_MESSAGE);
}
if(idNumber != -1) {
//CHECK IF ENTERED ID ALREADY EXISTS
boolean isCINDuplicate = false;
int counter;
for(counter = 0; counter < students.size(); counter++) {
if(idNumber == students.get(counter).getCIN()) {
isCINDuplicate = true;
break;
}
}
if(isCINDuplicate == false) {
Address address = getAddress();
if (address != null) {
students.add(new Student(name, address, idNumber));
}
}else {
JOptionPane.showMessageDialog(null, "Registered Student with Entered CIN Already Found", "Error: Duplicate CIN", JOptionPane.ERROR_MESSAGE, null);
}
}
}
}
}
public void addFaculty() {
String name = JOptionPane.showInputDialog(null, "Enter Faculty Member Name:");
if(name != null && name.length() > 0) {
int idNumber = -1;
String idNumberString = JOptionPane.showInputDialog(null, "Enter Employee ID:");
if(idNumberString != null) {
try{
idNumber = Integer.parseInt(idNumberString);
}catch(NumberFormatException e) {
idNumber = -1;
JOptionPane.showMessageDialog(null, "Employee ID Must be Number", "Error: Int Required", JOptionPane.ERROR_MESSAGE);
}
if(idNumber != -1) {
//CHECK IF ENTERED ID IS DUPLICATE
boolean isIdDuplicate = false;
int counter;
for(counter = 0; counter < faculty.size(); counter++) {
if(idNumber == faculty.get(counter).getEmployeeId()) {
isIdDuplicate = true;
break;
}
}
if(isIdDuplicate == false) {
Address address = getAddress();
if (address != null) {
faculty.add(new FacultyMember(name, address, idNumber));
}
}else {
JOptionPane.showMessageDialog(null, "Registered Employee with Entered ID Already Found", "Error: Duplicate ID", JOptionPane.ERROR_MESSAGE, null);
}
}
}
}
}
private void addCourse() {
String name = JOptionPane.showInputDialog(null, "Enter Course Identifier:");
if(name != null && name.length() > 0) {
Object[] menuChoices = {1,2,3,4,5,6,7,8};
Object courseUnits = JOptionPane.showInputDialog(null, "Select Number of Units:", "Pick Units",
JOptionPane.QUESTION_MESSAGE, null, menuChoices, menuChoices[0]);
if(courseUnits != null) {
courses.add(new Course(name, (int)courseUnits));
}
}
}
// DELETE METHODS
private void deleteStudent() {
Object[] options = students.toArray();
Object choice = JOptionPane.showInputDialog(null, "Pick a Student to Delete", "Delete Student",
JOptionPane.DEFAULT_OPTION, null, options, options[0]);
int index = students.indexOf(choice);
if (index != -1) {
students.remove(index);
JOptionPane.showMessageDialog(null, "Student Removed", "Deleted", JOptionPane.INFORMATION_MESSAGE);
}
}
private void deleteFaculty() {
Object[] options = faculty.toArray();
Object choice = JOptionPane.showInputDialog(null, "Pick a Faculty Member to Delete", "Delete Faculty Member",
JOptionPane.DEFAULT_OPTION, null, options, options[0]);
int index = faculty.indexOf(choice);
if (index != -1) {
faculty.remove(index);
JOptionPane.showMessageDialog(null, "Employee Removed", "Deleted", JOptionPane.INFORMATION_MESSAGE);
}
}
// GET ADDRESS FROM USER
public Address getAddress() {
int streetNumber = -1;
String streetNumberString = JOptionPane.showInputDialog(null, "Enter Street Number:");
if(streetNumberString != null) {
try {
streetNumber = Integer.parseInt(streetNumberString);
}catch(NumberFormatException e) {
streetNumber = -1;
JOptionPane.showMessageDialog(null, "Street Number Must be Number", "Error: Int Required", JOptionPane.ERROR_MESSAGE);
}
if(streetNumber > 0) {
String streetName = JOptionPane.showInputDialog(null, "Enter Street:");
if(streetName != null && streetName.length() > 0) {
String cityName = JOptionPane.showInputDialog(null, "Enter City:");
if(cityName != null && cityName.length() > 0) {
String stateName = JOptionPane.showInputDialog(null, "Enter State:");
if(stateName != null && stateName.length() > 0) {
String countryName = JOptionPane.showInputDialog(null, "Enter Country:");
if(countryName != null && countryName.length() > 0) {
return new Address(streetNumber, streetName, cityName, stateName, countryName);
}
}
}
}
}
}
return null;
}
// TESTING METHODS
public void insertStudent(String name, int streetnumber, String streetname, String city, String state,
String country, int cin) {
students.add(new Student(name, new Address(streetnumber, streetname, city, state, country), cin));
}
public void insertFaculty(String name, int streetnumber, String streetname, String city, String state,
String country, int cin) {
faculty.add(new FacultyMember(name, new Address(streetnumber, streetname, city, state, country), cin));
}
public void insertCourse(String name, int units) {
courses.add(new Course(name, units));
}
}

58
CS2012 Lab 5/.gitignore vendored Normal file
View File

@ -0,0 +1,58 @@
.metadata
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.settings/
.loadpath
.recommenders
# External tool builders
.externalToolBuilders/
# Locally stored "Eclipse launch configurations"
*.launch
# PyDev specific (Python IDE for Eclipse)
*.pydevproject
# CDT-specific (C/C++ Development Tooling)
.cproject
# CDT- autotools
.autotools
# Java annotation processor (APT)
.factorypath
# PDT-specific (PHP Development Tools)
.buildpath
# sbteclipse plugin
.target
# Tern plugin
.tern-project
# TeXlipse plugin
.texlipse
# STS (Spring Tool Suite)
.springBeans
# Code Recommenders
.recommenders/
# Annotation Processing
.apt_generated/
# Scala IDE specific (Scala & Java development for Eclipse)
.cache-main
.scala_dependencies
.worksheet
.classpath
.project

View File

@ -0,0 +1,202 @@
package monsterattack;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class AttackMonitor {
private List<MonsterAttack> attacks = new ArrayList<MonsterAttack>();
private Scanner scan = new Scanner(System.in);
public void monitor() {
int menuChoice = 0;
do {
System.out.println("-------------------");
System.out.println("0: quit");
System.out.println("1: add monster");
System.out.println("2: view monsters");
System.out.println("3: delete monster");
System.out.println("4: import from csv");
System.out.println("5: export to csv");
System.out.print("Enter Option: ");
while (!scan.hasNextInt()) {
scan.nextLine();
System.out.println("-------------------");
System.out.println(" ERROR: Enter Int");
System.out.println("-------------------");
System.out.print("Enter Option: ");
}
menuChoice = scan.nextInt();
switch (menuChoice) {
case 0:
break;
case 1:
addMonster();
break;
case 2:
showMonsters();
break;
case 3:
deleteMonster();
break;
case 4:
importCSV();
break;
case 5:
exportCSV();
break;
}
} while (menuChoice != 0);
}
public void insertMonster(String dateOfAttack, String nameOfMonster, String locationOfAttack, String nameOfReporter) {
MonsterAttack monster = new MonsterAttack(dateOfAttack, nameOfMonster, locationOfAttack, nameOfReporter);
attacks.add(monster);
}
private void addMonster() {
System.out.println("-------------------");
System.out.print("Enter Name Of Monster: ");
String nameOfMonster = scan.next();
String dateOfAttack = null;
do {
System.out.print("Enter Date of Attack (MM/DD/YYYY): ");
dateOfAttack = scan.next();
if(dateOfAttack.length() > 10) {
dateOfAttack = null;
System.out.println(" ERROR: String too long");
}
}while(dateOfAttack == null);
System.out.print("Enter Location Of Attack: ");
String locationOfAttack = scan.next();
System.out.print("Enter Name Of Reporter: ");
String nameOfReporter = scan.next();
attacks.add(new MonsterAttack(dateOfAttack, nameOfMonster, locationOfAttack, nameOfReporter));
}
private void showMonsters() {
System.out.println("-------------------");
if (attacks.size() != 0) {
for (int i = 0; i < attacks.size(); i++) {
// System.out.print('\t');
System.out.println(attacks.get(i));
}
} else {
System.out.println(" ERROR: List Empty");
}
}
private void deleteMonster() {
showMonsters();
System.out.println("-------------------");
System.out.print("Enter ID of Attack from list above: ");
while (!scan.hasNextInt()) {
scan.nextLine();
System.out.println("ERROR: Enter Int");
}
int idToDelete = scan.nextInt();
boolean found = false;
for (int counter = 0; counter < attacks.size(); counter++) {
int attackId = attacks.get(counter).getAttackId();
if (attackId == idToDelete) {
found = true;
attacks.remove(counter);
// break;
}
// counter++;
}
if (found == false)
System.out.println("-------------------\nAttack of given ID not found");
}
private void importCSV() {
System.out.println("-------------------");
System.out.println("Enter Path of File to Import From:");
String filePath = scan.next();
attacks.clear();
try {
File file = new File(filePath);
Scanner fscan = new Scanner(file);
String attackLine = null;
String[] attackData = null;
int attackId;
while(fscan.hasNextLine()) {
attackLine = fscan.nextLine();
attackData = attackLine.split(",");
attackId = Integer.parseInt(attackData[0]);
MonsterAttack attack = new MonsterAttack(attackData[1], attackData[2], attackData[3], attackData[4]);
attack.setAttackId(attackId);
attacks.add(attack);
}
fscan.close();
}catch(IOException e) {
System.out.println(" ERROR: " + e);
}catch(NumberFormatException e) {
System.out.println(" ERROR: Invalid File " + e);
}catch(ArrayIndexOutOfBoundsException e) {
System.out.println(" ERROR: Not Enough Data For Attack Found (5 Columns Expected) " + e);
}
}
private void exportCSV() {
System.out.println("-------------------");
System.out.println("Enter Path of File to Export To:");
String filePath = scan.next();
try {
File file = new File(filePath);
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
int counter;
MonsterAttack attack;
for(counter = 0; counter < attacks.size(); counter++) {
attack = attacks.get(counter);
writer.write(attack.getAttackId() + "," +
attack.getMonthOfAttack() + "/" +
attack.getDayOfAttack() + "/" +
attack.getYearOfAttack() + "," +
attack.getNameOfMonster() + "," +
attack.getAttackLocation() + "," +
attack.getReporterName());
if(counter != (attacks.size() - 1)) writer.newLine();
}
writer.close();
System.out.println("File Written Successfully");
}
catch(IOException e){
System.out.println(" ERROR: " + e);
System.out.println("File Writing Aborted");
}
}
}

View File

@ -0,0 +1,110 @@
package monsterattack;
public class MonsterAttack {
private int attackId;
private int dayOfAttack;
private int monthOfAttack;
private int yearOfAttack;
private String nameOfMonster;
private String attackLocation;
private String reporterName;
private static int lastAttackId = 0;
public MonsterAttack(String argDate, String argMonsterName, String argLocation, String argReporter) {
lastAttackId += 1;
this.setNameOfMonster(argMonsterName);
this.setAttackLocation(argLocation);
this.setReporterName(argReporter);
this.setAttackId(lastAttackId);
String[] arrOfDate = argDate.split("/", 4);
try {
if (arrOfDate.length == 3) {
this.setDayOfAttack(Integer.parseInt(arrOfDate[1]));
this.setMonthOfAttack(Integer.parseInt(arrOfDate[0]));
this.setYearOfAttack(Integer.parseInt(arrOfDate[2]));
}
} catch (Exception e) {
System.out.println(" ERROR: " + e);
System.out.println(" Error Setting Date, Default to 0/0/0");
}
}
public int getAttackId() {
return attackId;
}
public void setAttackId(int attackId) {
this.attackId = attackId;
}
public int getDayOfAttack() {
return dayOfAttack;
}
public void setDayOfAttack(int dayOfAttack) {
this.dayOfAttack = dayOfAttack;
}
public int getMonthOfAttack() {
return monthOfAttack;
}
public void setMonthOfAttack(int monthOfAttack) {
this.monthOfAttack = monthOfAttack;
}
public int getYearOfAttack() {
return yearOfAttack;
}
public void setYearOfAttack(int yearOfAttack) {
this.yearOfAttack = yearOfAttack;
}
public String getNameOfMonster() {
return nameOfMonster;
}
public void setNameOfMonster(String nameOfMonster) {
this.nameOfMonster = nameOfMonster;
}
public String getAttackLocation() {
return attackLocation;
}
public void setAttackLocation(String attackLocation) {
this.attackLocation = attackLocation;
}
public String getReporterName() {
return reporterName;
}
public void setReporterName(String reporterName) {
this.reporterName = reporterName;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(this.getAttackId());
sb.append("#: ");
sb.append(this.getNameOfMonster());
sb.append(" at ");
sb.append(this.getAttackLocation());
sb.append(" on ");
sb.append(this.getMonthOfAttack());
sb.append("/");
sb.append(this.getDayOfAttack());
sb.append("/");
sb.append(this.getYearOfAttack());
sb.append(", Reported By ");
sb.append(this.getReporterName());
String str = sb.toString();
return str;
}
}

View File

@ -0,0 +1,21 @@
package monsterattack;
public class MonsterAttackDriver {
public static void main(String[] args) {
AttackMonitor monitor = new AttackMonitor();
hardcodeAttacks(monitor);
monitor.monitor();
}
public static void hardcodeAttacks(AttackMonitor monitor) {
monitor.insertMonster("05/22/1980", "Godzilla1", "London", "Bill");
monitor.insertMonster("06/4/2005", "Godzilla2", "Paris", "Jeff");
monitor.insertMonster("07/6/1998", "Godzilla3", "Dublin", "Andy");
monitor.insertMonster("08/6/1998", "Godzilla4", "Dublin", "Andy");
monitor.insertMonster("09/6/1998", "Godzilla5", "Dublin", "Andy");
}
}

58
CS2012 Lab 7/.gitignore vendored Normal file
View File

@ -0,0 +1,58 @@
.metadata
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.settings/
.loadpath
.recommenders
# External tool builders
.externalToolBuilders/
# Locally stored "Eclipse launch configurations"
*.launch
# PyDev specific (Python IDE for Eclipse)
*.pydevproject
# CDT-specific (C/C++ Development Tooling)
.cproject
# CDT- autotools
.autotools
# Java annotation processor (APT)
.factorypath
# PDT-specific (PHP Development Tools)
.buildpath
# sbteclipse plugin
.target
# Tern plugin
.tern-project
# TeXlipse plugin
.texlipse
# STS (Spring Tool Suite)
.springBeans
# Code Recommenders
.recommenders/
# Annotation Processing
.apt_generated/
# Scala IDE specific (Scala & Java development for Eclipse)
.cache-main
.scala_dependencies
.worksheet
.classpath
.project

View File

@ -0,0 +1,187 @@
package mymath;
public class MyFraction implements MyMath<MyFraction>{
private int numerator;
private int denominator;
private char sign;
public MyFraction(int numerator, int denominator, char sign) {
this.numerator = Math.abs(numerator);
if(denominator == 0) throw new IllegalArgumentException("Trying to Enter Denominator of 0");
this.denominator = Math.abs(denominator);
if(sign == '+' || sign == '-')
this.sign = sign;
else throw new IllegalArgumentException("Invalid Sign Character Entererd (+, -)");
}
@Override
public MyFraction add(MyFraction o) {
if(sign == '+' && o.getSign() == '-') { // a + (-b) = a - b
return subtract(new MyFraction(o.getNumerator(), o.getDenominator(), '+'));
}
if(sign == '-' && o.getSign() == '+') { // (-a) + b = b - a
return o.subtract(new MyFraction(getNumerator(), getDenominator(), '+'));
}
if(sign == '-' && o.getSign() == '-') { // (-a) + (-b) = -(a + b)
MyFraction newFraction = reduceFraction().getMultipliedByDenominator(o.getDenominator());
MyFraction newInputFraction = o.reduceFraction().getMultipliedByDenominator(getDenominator());
return new MyFraction(newFraction.getNumerator() + newInputFraction.getNumerator(), newFraction.getDenominator(), '-').reduceFraction();
}
if(sign == '+' && o.getSign() == '+') { // a + b = a + b
MyFraction newFraction = reduceFraction().getMultipliedByDenominator(o.getDenominator());
MyFraction newInputFraction = o.reduceFraction().getMultipliedByDenominator(getDenominator());
return new MyFraction(newFraction.getNumerator() + newInputFraction.getNumerator(), newFraction.getDenominator(), '+').reduceFraction();
}
return null;
}
@Override
public MyFraction subtract(MyFraction o) {
if(sign == '+' && o.getSign() == '-') { // a - (-b) = a + b
return add(new MyFraction(o.getNumerator(), o.getDenominator(), '+'));
}
if(sign == '-' && o.getSign() == '+') { // (-a) - b = -(b + a)
return o.add(new MyFraction(getNumerator(), getDenominator(), '+')).toggleSign().reduceFraction();
}
if(sign == '-' && o.getSign() == '-') { // (-a) - (-b) = b - a
MyFraction newFraction = reduceFraction().getMultipliedByDenominator(o.getDenominator()); // a
MyFraction newInputFraction = o.reduceFraction().getMultipliedByDenominator(getDenominator()); // b
char sign;
if(newInputFraction.getNumerator() > newFraction.getNumerator()) sign = '+';
else sign = '-';
return new MyFraction(Math.abs(newInputFraction.getNumerator() - newFraction.getNumerator()), newFraction.getDenominator(), sign).reduceFraction();
}
if(sign == '+' && o.getSign() == '+') { // a - b = a - b
MyFraction newFraction = reduceFraction().getMultipliedByDenominator(o.getDenominator());
MyFraction newInputFraction = o.reduceFraction().getMultipliedByDenominator(getDenominator());
char sign;
if(newFraction.getNumerator() > newInputFraction.getNumerator()) sign = '+';
else sign = '-';
return new MyFraction(Math.abs(newFraction.getNumerator() - newInputFraction.getNumerator()), newFraction.getDenominator(), sign).reduceFraction();
}
return null;
}
public MyFraction toggleSign() {
if(getSign() == '+') return new MyFraction(getNumerator(), getDenominator(), '-');
else return new MyFraction(getNumerator(), getDenominator(), '+');
}
private MyFraction getMultipliedByDenominator(int denominatorCoeff) {
return new MyFraction((getNumerator() * denominatorCoeff), (getDenominator() * denominatorCoeff), sign);
}
@Override
public MyFraction multiply(MyFraction o) {
int newNumerator = this.getNumerator() * o.getNumerator();
int newDenominator = this.getDenominator() * o.getDenominator();
char newSign = 0;
if(this.getSign() == '+' && o.getSign() == '+') newSign = '+';
if(this.getSign() == '+' && o.getSign() == '-') newSign = '-';
if(this.getSign() == '-' && o.getSign() == '+') newSign = '-';
if(this.getSign() == '-' && o.getSign() == '-') newSign = '+';
return (new MyFraction(newNumerator, newDenominator, newSign)).reduceFraction();
}
@Override
public MyFraction divide(MyFraction o) {
if(o.getNumerator() == 0) throw new IllegalArgumentException("Trying to Divide by 0");
return this.multiply(new MyFraction(o.getDenominator(), o.getNumerator(), o.getSign()));
}
public MyFraction reduceFraction() {
//TODO look into stronger solution than list of primes
int[] array = {2,3,5,7,9,11,13,17,19,23,29,31,37,41,43,47,53};
int newNumerator = this.numerator;
int newDenominator = this.denominator;
boolean isSmallest = false;
while(!isSmallest) {
isSmallest = true;
for(int num : array) {
if(((newNumerator % num) == 0 ) && ((newDenominator % num) == 0 )) {
newNumerator = newNumerator / num;
newDenominator = newDenominator / num;
isSmallest = false;
}
}
if(newNumerator == newDenominator) {
newNumerator = 1;
newDenominator = 1;
isSmallest = true;
}
}
return new MyFraction(newNumerator, newDenominator, sign);
}
public int getNumerator() {
return numerator;
}
public void setNumerator(int numerator) {
if(numerator >= 0) this.numerator = numerator;
else System.err.println("Invalid Numerator: Negative Value Not Acceptable, Value Unchanged");
}
public int getDenominator() {
return denominator;
}
public void setDenominator(int denominator) {
if(denominator > 0) this.denominator = denominator;
else if(denominator == 0) System.err.println("Invalid Denominator: 0 Not Acceptable");
else System.err.println("Invalid Denominator: Negative Value Not Acceptable, Value Unchanged");
}
public char getSign() {
return sign;
}
public void setSign(char sign) {
if(sign == '+') this.sign = '+';
else if(sign == '-') this.sign = '-';
else System.err.println("Invalid Sign Character Entererd (+, -): sign unchanged");
}
@Override
public String toString() {
if(sign == '-') return "-" + numerator + "/" + denominator;
else return numerator + "/" + denominator;
}
@Override
public boolean equals(Object obj) {
if(obj.getClass() != this.getClass()) return false;
MyFraction thisSmallest = reduceFraction();
MyFraction fraction = ((MyFraction)obj).reduceFraction();
if(thisSmallest.getNumerator() == fraction.getNumerator())
if(thisSmallest.getDenominator() == fraction.getDenominator())
if(thisSmallest.getSign() == fraction.getSign())
return true;
return false;
}
}

View File

@ -0,0 +1,11 @@
package mymath;
public interface MyMath<T> {
public T add(T o);
public T subtract(T o);
public T divide(T o);
public T multiply(T o);
}

View File

@ -0,0 +1,168 @@
package mymath;
import java.lang.reflect.Array;
import java.util.Arrays;
public class MySet implements MyMath<MySet> { // 2147483647
private int[] numbersSet;
public MySet(int[] inputNumbers) {
if(inputNumbers != null)
numbersSet = checkForDuplicates(inputNumbers);
}
@Override
public boolean equals(Object obj) {
if(obj.getClass() != this.getClass()) return false;
MySet o = (MySet) obj;
int[] importedSet = o.getNumbersSet();
if((importedSet == null) && (numbersSet == null)) return true;
boolean equal;
Arrays.sort(importedSet, 0, importedSet.length - 1);
Arrays.sort(numbersSet, 0, importedSet.length - 1);
int count = 0;
for (int i = 0; i < importedSet.length; i++) {
if (numbersSet[i] == importedSet[i]) {
count++;
}
}
if (count == importedSet.length) {
equal = true;
} else {
equal = false;
}
return equal;
}
public int[] stringToInt(String inputNumbers) {
String[] array1 = inputNumbers.split(" ");
int[] numbers = new int[array1.length];
try {
for (int i = 0; i < array1.length; i++) {
numbers[i] = Integer.parseInt(array1[i]);
}
} catch (NumberFormatException ex) {
// System.out.print("Does not exist");
return null;
}
Arrays.sort(numbers);
return numbers;
}
public int[] checkForDuplicates(int[] unFilteredSet) {
String noDuplicates = "";
Arrays.sort(unFilteredSet, 0, unFilteredSet.length - 1);
for (int i = 0; i < unFilteredSet.length - 1; i++) {
if (unFilteredSet[i] != unFilteredSet[i + 1]) {
noDuplicates += unFilteredSet[i] + " ";
}
}
noDuplicates += unFilteredSet[unFilteredSet.length - 1];
int[] noTwos = stringToInt(noDuplicates);
return noTwos;
}
public MySet add(MySet o) {
int[] importedSet = o.getNumbersSet();
String combineSets = "";
for (int i = 0; i < importedSet.length; i++) {
combineSets += importedSet[i] + " ";
}
for (int i = 0; i < numbersSet.length; i++) {
combineSets += numbersSet[i] + " ";
}
MySet union = new MySet(stringToInt(combineSets));
return union;
}
public MySet subtract(MySet o) {
int[] importedSet = o.getNumbersSet();
String complement = "";
for (int i = 0; i < numbersSet.length; i++) {
int count = 0;
for (int j = 0; j < importedSet.length; j++) {
if (numbersSet[i] == importedSet[j]) {
count++;
}
}
if (count == 0) {
complement += numbersSet[i] + " ";
}
}
MySet complements = new MySet(stringToInt(complement));
return complements;
}
public MySet multiply(MySet o) {
int[] importedSet = o.getNumbersSet();
String symmetricDifference = "";
for (int i = 0; i < numbersSet.length; i++) {
int count = 0;
for (int j = 0; j < importedSet.length; j++) {
if (numbersSet[i] == importedSet[j]) {
count++;
}
}
if (count == 0) {
symmetricDifference += numbersSet[i] + " ";
}
}
for (int i = 0; i < importedSet.length; i++) {
int count = 0;
for (int j = 0; j < numbersSet.length; j++) {
if (importedSet[i] == numbersSet[j]) {
count++;
}
}
if (count == 0) {
symmetricDifference += importedSet[i] + " ";
}
}
MySet symmetricD = new MySet(stringToInt(symmetricDifference));
return symmetricD;
}
public MySet divide(MySet o) {
int[] importedSet = o.getNumbersSet();
String intersection = "";
for (int i = 0; i < numbersSet.length; i++) {
int count = 0;
for (int j = 0; j < importedSet.length; j++) {
if (numbersSet[i] == importedSet[j]) {
count++;
}
}
if (count != 0) {
intersection += numbersSet[i] + " ";
}
}
MySet intersectionSet = new MySet(stringToInt(intersection));
return intersectionSet;
}
public String toString() {
return java.util.Arrays.toString(numbersSet);
}
public int[] getNumbersSet() {
return numbersSet;
}
public void setNumbersSet(int[] numbersSet) {
this.numbersSet = numbersSet;
}
}

View File

@ -0,0 +1,336 @@
package mymath.test;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import mymath.MyFraction;
class MyFractionTests {
@Test
void testCreatable() {
MyFraction fraction = new MyFraction(1,1, '+');
assertNotNull(fraction);
}
@Test
void testNegativeNumerator() {
MyFraction fraction = new MyFraction(-1,5, '+');
assertSame(fraction.getNumerator(), 1);
}
@Test
void testNegativeDenominator() {
MyFraction fraction = new MyFraction(1,-5, '+');
assertSame(fraction.getDenominator(), 5);
}
@Test
void test0Denominator() {
String message = null;
try {
MyFraction fraction = new MyFraction(1,0, '+');
}catch(IllegalArgumentException e) {
message = e.getMessage();
System.err.println("Test Construct with 0 Denominator: " + message);
}
assertEquals(message, "Trying to Enter Denominator of 0");
}
@Test
void testInvalidSign() {
String message = null;
try {
MyFraction fraction = new MyFraction(2,5, 'f');
}catch(IllegalArgumentException e) {
message = e.getMessage();
System.err.println("Test Invalid Sign Char: " + message);
}
assertEquals(message, "Invalid Sign Character Entererd (+, -)");
}
@Test
void testNumeratorGet() {
MyFraction fraction = new MyFraction(1,1, '+');
assertSame(fraction.getNumerator(), 1);
}
@Test
void testNumeratorSet() {
MyFraction fraction = new MyFraction(1,1, '+');
fraction.setNumerator(5);
assertSame(fraction.getNumerator(), 5);
}
@Test
void testDenominatorGet() {
MyFraction fraction = new MyFraction(1,1, '+');
assertSame(fraction.getDenominator(), 1);
}
@Test
void testDenominatorSet() {
MyFraction fraction = new MyFraction(1,1, '+');
fraction.setDenominator(5);
assertSame(fraction.getDenominator(), 5);
}
@Test
void testSignGet() {
MyFraction fraction = new MyFraction(1,1, '+');
assertEquals(fraction.getSign(), '+');
}
@Test
void testSignSet() {
MyFraction fraction = new MyFraction(1,1, '+');
fraction.setSign('-');
assertEquals(fraction.getSign(), '-');
}
@Test
void testToStringPositive() {
MyFraction fraction = new MyFraction(2,3, '+');
assertEquals(fraction.toString(), "2/3");
}
@Test
void testToStringNegative() {
MyFraction fraction = new MyFraction(1,3, '-');
assertEquals(fraction.toString(), "-1/3");
}
@Test
void testEquals() {
MyFraction fraction = new MyFraction(2,3, '+');
assertEquals(fraction, new MyFraction(2, 3, '+'));
}
@Test
void testEqualsWhenNotReduced() {
MyFraction fraction = new MyFraction(2,3, '+');
assertEquals(fraction, new MyFraction(40, 60, '+'));
}
@Test
void testEqualsNegative() {
MyFraction fraction = new MyFraction(2,3, '-');
assertEquals(fraction, new MyFraction(2, 3, '-'));
}
@Test
void testSmallest() {
MyFraction fraction = new MyFraction(2,10, '+');
MyFraction fractionSmaller = fraction.reduceFraction();
assertEquals(fractionSmaller, new MyFraction(1,5,'+'));
}
@Test
void testSmallest2() {
MyFraction fraction = new MyFraction(98,21, '+');
MyFraction fractionSmaller = fraction.reduceFraction();
assertEquals(fractionSmaller, new MyFraction(14,3,'+'));
}
@Test
void testSmallestNegative() {
MyFraction fraction = new MyFraction(3,15, '-');
MyFraction fractionSmaller = fraction.reduceFraction();
assertEquals(fractionSmaller, new MyFraction(1,5,'-'));
}
@Test
void testSmallestWhenSmall() {
MyFraction fraction = new MyFraction(5,7, '+');
MyFraction fractionSmaller = fraction.reduceFraction();
assertEquals(fractionSmaller, new MyFraction(5,7,'+'));
}
@Test
void testMuliplyPosPos() {
MyFraction fraction = new MyFraction(5,7, '+');
MyFraction fraction2 = new MyFraction(1,2, '+');
MyFraction fractionProduct = fraction.multiply(fraction2);
assertEquals(fractionProduct, new MyFraction(5,14,'+'));
}
@Test
void testMuliplyPosNeg() {
MyFraction fraction = new MyFraction(5,7, '+');
MyFraction fraction2 = new MyFraction(1,2, '-');
MyFraction fractionProduct = fraction.multiply(fraction2);
assertEquals(fractionProduct, new MyFraction(5,14,'-'));
}
@Test
void testMuliplyNegPos() {
MyFraction fraction = new MyFraction(5,7, '-');
MyFraction fraction2 = new MyFraction(1,2, '+');
MyFraction fractionProduct = fraction.multiply(fraction2);
assertEquals(fractionProduct, new MyFraction(5,14,'-'));
}
@Test
void testMuliplyNegNeg() {
MyFraction fraction = new MyFraction(5,7, '-');
MyFraction fraction2 = new MyFraction(1,2, '-');
MyFraction fractionProduct = fraction.multiply(fraction2);
assertEquals(fractionProduct, new MyFraction(5,14,'+'));
}
@Test
void testMuliplyForSmallest() {
MyFraction fraction = new MyFraction(4,10, '+');
MyFraction fraction2 = new MyFraction(2,5, '+');
MyFraction fractionProduct = fraction.multiply(fraction2);
assertEquals(fractionProduct, new MyFraction(4,25,'+'));
}
@Test
void testMuliplyBy0() {
MyFraction fraction = new MyFraction(4,10, '+');
MyFraction fraction2 = new MyFraction(0,5, '+');
MyFraction fractionProduct = fraction.multiply(fraction2);
assertEquals(fractionProduct, new MyFraction(0,1,'+'));
}
@Test
void testDivide() {
MyFraction fraction = new MyFraction(2,7, '+');
MyFraction fraction2 = new MyFraction(1,2, '+');
MyFraction fractionProduct = fraction.divide(fraction2);
assertEquals(fractionProduct, new MyFraction(4,7,'+'));
}
@Test
void testDivide2() {
MyFraction fraction = new MyFraction(4,1, '+');
MyFraction fraction2 = new MyFraction(2,1, '+');
MyFraction fractionProduct = fraction.divide(fraction2);
assertEquals(fractionProduct, new MyFraction(2,1,'+'));
}
@Test
void testDivideNegative() {
MyFraction fraction = new MyFraction(2,7, '+');
MyFraction fraction2 = new MyFraction(1,2, '-');
MyFraction fractionProduct = fraction.divide(fraction2);
assertEquals(fractionProduct, new MyFraction(4,7,'-'));
}
@Test
void testDivideBy0() {
MyFraction fraction = new MyFraction(2,7, '+');
MyFraction fraction2 = new MyFraction(0,2, '+');
String message = null;
try {
MyFraction fractionProduct = fraction.divide(fraction2);
}catch(IllegalArgumentException e) {
message = e.getMessage();
System.err.println("Test Divide by 0: " + message);
}
assertEquals(message, "Trying to Divide by 0");
}
@Test
void testAddPosPos() {
MyFraction fraction = new MyFraction(1,2, '+');
MyFraction fraction2 = new MyFraction(1,4, '+');
MyFraction fractionAdd = fraction.add(fraction2);
assertEquals(fractionAdd, new MyFraction(3,4,'+'));
}
@Test
void testAddPosNeg() {
MyFraction fraction = new MyFraction(5,7, '+');
MyFraction fraction2 = new MyFraction(1,7, '-');
MyFraction fractionAdd = fraction.add(fraction2);
assertEquals(fractionAdd, new MyFraction(4,7,'+'));
}
@Test
void testAddNegPos() {
MyFraction fraction = new MyFraction(15,17, '-');
MyFraction fraction2 = new MyFraction(1,17, '+');
MyFraction fractionAdd = fraction.add(fraction2);
assertEquals(fractionAdd, new MyFraction(14,17,'-'));
}
@Test
void testAddNegNeg() {
MyFraction fraction = new MyFraction(15,17, '-');
MyFraction fraction2 = new MyFraction(2,17, '-');
MyFraction fractionAdd = fraction.add(fraction2);
assertEquals(fractionAdd, new MyFraction(1,1,'-'));
}
@Test
void testAddNegToPos() {
MyFraction fraction = new MyFraction(15,17, '-');
MyFraction fraction2 = new MyFraction(19,17, '+');
MyFraction fractionAdd = fraction.add(fraction2);
assertEquals(fractionAdd, new MyFraction(4,17,'+'));
}
@Test
void testAddPosToNeg() {
MyFraction fraction = new MyFraction(4,17, '+');
MyFraction fraction2 = new MyFraction(8,17, '-');
MyFraction fractionAdd = fraction.add(fraction2);
assertEquals(fractionAdd, new MyFraction(4,17,'-'));
}
@Test
void testSubtractPosPos() {
MyFraction fraction = new MyFraction(15,17, '+');
MyFraction fraction2 = new MyFraction(2,17, '+');
MyFraction fractionAdd = fraction.subtract(fraction2);
assertEquals(fractionAdd, new MyFraction(13,17,'+'));
}
@Test
void testSubtractPosNeg() {
MyFraction fraction = new MyFraction(15,17, '+');
MyFraction fraction2 = new MyFraction(5,17, '-');
MyFraction fractionAdd = fraction.subtract(fraction2);
assertEquals(fractionAdd, new MyFraction(20,17,'+'));
}
@Test
void testSubtractNegPos() {
MyFraction fraction = new MyFraction(15,17, '-');
MyFraction fraction2 = new MyFraction(3,17, '+');
MyFraction fractionAdd = fraction.subtract(fraction2);
assertEquals(fractionAdd, new MyFraction(18,17,'-'));
}
@Test
void testSubtractNegNeg() {
MyFraction fraction = new MyFraction(15,17, '-');
MyFraction fraction2 = new MyFraction(2,17, '-');
MyFraction fractionAdd = fraction.subtract(fraction2);
assertEquals(fractionAdd, new MyFraction(13,17,'-'));
}
@Test
void testSubtractNegtoPos() {
MyFraction fraction = new MyFraction(15,17, '-');
MyFraction fraction2 = new MyFraction(20,17, '-');
MyFraction fractionAdd = fraction.subtract(fraction2);
assertEquals(fractionAdd, new MyFraction(5,17,'+'));
}
@Test
void testSubtractPostoNeg() {
MyFraction fraction = new MyFraction(15,17, '+');
MyFraction fraction2 = new MyFraction(16,17, '+');
MyFraction fractionAdd = fraction.subtract(fraction2);
assertEquals(fractionAdd, new MyFraction(1,17,'-'));
}
}

View File

@ -0,0 +1,305 @@
package mymath.test;
//import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import mymath.MySet;
class MySetTests {
@Test
void testCreatable() {
int[] num = { 1, 2, 3 };
MySet set = new MySet(num);
assertNotNull(set);
}
@Test
void testToString() {
int[] num = { 1, 2, 3, 4 };
MySet set = new MySet(num);
assertEquals(set.toString(), "[1, 2, 3, 4]");
}
@Test
void testEquals() {
int[] num = { 1, 2, 3 };
int[] num2 = { 1, 2, 3 };
MySet set = new MySet(num);
MySet set2 = new MySet(num2);
assertEquals(set, set2);
}
@Test
void test0Array() {
int[] num = { 0 };
MySet set = new MySet(null);
assertNotNull(set);
}
@Test
void testNegNum() {
int[] num = { -1, 2, 3 };
MySet set = new MySet(num);
// System.out.println(set);
assertEquals(set.toString(), "[-1, 2, 3]");
}
@Test
void testGetNumberSet() {
int[] num = { 1, 2, 3 };
MySet set = new MySet(num);
int[] getNum = set.getNumbersSet();
assertArrayEquals(num, getNum);
}
@Test
void testGetNullSet() {
MySet set = new MySet(null);
int[] getNum = set.getNumbersSet();
assertNull(getNum);
}
@Test
void testSetNumberSet() {
int[] num = { 1, 2, 3 };
MySet set = new MySet(num);
int[] newNum = { 1, 2, 3, 4 };
set.setNumbersSet(newNum);
int[] getNum = set.getNumbersSet();
assertArrayEquals(newNum, getNum);
}
@Test
void testDuplicateElement() {
int[] num = { 1, 2, 2, 3 };
MySet set = new MySet(num);
int[] expected = { 1, 2, 3 };
MySet setExpected = new MySet(expected);
assertEquals(set, setExpected);
}
@Test
void testDuplicateElement2() {
int[] num = { 1, 2, 2, 2, 3, 3 };
MySet set = new MySet(num);
int[] expected = { 1, 2, 2, 3 };
MySet setExpected = new MySet(expected);
assertEquals(set, setExpected);
}
@Test
void testCheckForDuplicatesMethod() {
int[] num = { 1, 2, 2, 3 };
MySet set = new MySet(num);
int[] filtered = set.checkForDuplicates(num);
int[] expected = { 1, 2, 3 };
assertArrayEquals(filtered, expected);
}
@Test
void testAddition() {
int[] num = { 1, 2, 3 };
MySet set = new MySet(num);
int[] num2 = { 4, 5, 6 };
MySet set2 = new MySet(num2);
int[] expected = { 1, 2, 3, 4, 5, 6 };
MySet setExpected = new MySet(expected);
MySet answer = set.add(set2);
// System.out.println(answer);
assertEquals(answer, setExpected);
}
@Test
void testAddSameSets() {
int[] num = { 1, 2, 3 };
MySet set = new MySet(num);
int[] num2 = { 1, 2, 3 };
MySet set2 = new MySet(num2);
int[] expected = { 1, 2, 3 };
MySet setExpected = new MySet(expected);
MySet answer = set.add(set2);
assertEquals(answer, setExpected);
}
@Test
void testAddWithOverlap() {
int[] num = { 1, 2, 3 };
MySet set = new MySet(num);
int[] num2 = { 3, 4, 5, 6 };
MySet set2 = new MySet(num2);
int[] expected = { 1, 2, 3, 4, 5, 6 };
MySet setExpected = new MySet(expected);
MySet answer = set.add(set2);
// System.out.println(answer);
assertEquals(answer, setExpected);
}
@Test
void testSubtraction() {
int[] num = { 1, 2, 3, 4, 5, 6 };
MySet set = new MySet(num);
int[] num2 = { 3, 4, 5, 6 };
MySet set2 = new MySet(num2);
int[] expected = { 1, 2 };
MySet setExpected = new MySet(expected);
MySet answer = set.subtract(set2);
assertEquals(answer, setExpected);
}
@Test
void testSubtractSameSets() {
int[] num = { 1, 2, 3, 4, 5, 6 };
MySet set = new MySet(num);
int[] num2 = { 1, 2, 3, 4, 5, 6 };
MySet set2 = new MySet(num2);
MySet setExpected = new MySet(null);
MySet answer = set.subtract(set2);
// System.out.println(answer);
assertEquals(answer, setExpected);
}
@Test
void testSubtractNoOverlap() {
int[] num = { 1, 2 };
MySet set = new MySet(num);
int[] num2 = { 3, 4, 5, 6 };
MySet set2 = new MySet(num2);
int[] expected = { 1, 2 };
MySet setExpected = new MySet(expected);
MySet answer = set.subtract(set2);
assertEquals(answer, setExpected);
}
@Test
void testMultiply() {
int[] num = { 1, 2, 3, 4, 5, 6 };
MySet set = new MySet(num);
int[] num2 = { 3, 4, 5, 8, 9 };
MySet set2 = new MySet(num2);
int[] expected = { 1, 2, 6, 8, 9 };
MySet setExpected = new MySet(expected);
MySet answer = set.multiply(set2);
assertEquals(answer, setExpected);
}
@Test
void testMultiplySameSet() {
int[] num = { 3, 4, 5, 6 };
MySet set = new MySet(num);
int[] num2 = { 3, 4, 5, 6 };
MySet set2 = new MySet(num2);
MySet setExpected = new MySet(null);
MySet answer = set.multiply(set2);
assertEquals(answer, setExpected);
}
@Test
void testMultiplyNoOverlap() {
int[] num = { 1, 2, 3 };
MySet set = new MySet(num);
int[] num2 = { 4, 5, 6 };
MySet set2 = new MySet(num2);
int[] numExpected = { 1, 2, 3, 4, 5, 6 };
MySet setExpected = new MySet(numExpected);
MySet answer = set.multiply(set2);
assertEquals(answer, setExpected);
}
@Test
void testDivide() {
int[] num = { 1, 2, 3, 4, 5, 6 };
MySet set = new MySet(num);
int[] num2 = { 3, 4, 5, 6, 7, 8 };
MySet set2 = new MySet(num2);
int[] expected = { 3, 4, 5, 6 };
MySet setExpected = new MySet(expected);
MySet answer = set.divide(set2);
assertEquals(setExpected, answer);
}
@Test
void testDivideSameSet() {
int[] num = { 1, 2, 3 };
MySet set = new MySet(num);
int[] num2 = { 1, 2, 3 };
MySet set2 = new MySet(num2);
int[] expected = { 1, 2, 3 };
MySet setExpected = new MySet(expected);
MySet answer = set.divide(set2);
assertEquals(setExpected, answer);
}
@Test
void testDivideNoOverlap() {
int[] num = { 1, 2, 3 };
MySet set = new MySet(num);
int[] num2 = { 4, 5, 6 };
MySet set2 = new MySet(num2);
MySet setExpected = new MySet(null);
MySet answer = set.divide(set2);
assertEquals(setExpected, answer);
}
}

View File

@ -0,0 +1,189 @@
package mymath.test;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import mymath.MyFraction;
class TestsMyFraction {
@Test
public void testNumeratorConstructor() {
MyFraction test = new MyFraction(2, 3, '+');
assertNotNull(test.getNumerator());
}
@Test
public void testDenominatorConstructor() {
MyFraction test = new MyFraction(2, 3, '+');
assertNotNull(test.getDenominator());
}
@Test
public void testSignConstructor() {
MyFraction test = new MyFraction(2, 3, '-');
assertNotNull(test.getSign());
}
@Test
public void testFractionReduction() {
MyFraction test = new MyFraction(3, 6, '+');
MyFraction reduced = new MyFraction(1, 2, '+');
assertTrue(test.equals(reduced));
}
@Test
public void testNumerator() {
MyFraction test = new MyFraction(2, 4, '+');
assertSame(test.getNumerator(), 2);
}
@Test
public void testDenominator() {
MyFraction test = new MyFraction(1, 4, '-');
assertSame(test.getDenominator(), 4);
}
@Test
public void testSign() {
MyFraction test = new MyFraction(1, 2, '+');
assertSame(test.getSign(), '+');
}
@Test
public void testAddDoublePositive() {
MyFraction test = new MyFraction(1, 4, '+');
MyFraction add = new MyFraction(3, 4, '+');
MyFraction result = new MyFraction(1, 1, '+');
assertTrue(result.equals(test.add(add)));
}
@Test
public void testAddPositiveNegative() {
MyFraction test = new MyFraction(1, 4, '+');
MyFraction add = new MyFraction(3, 4, '-');
MyFraction result = new MyFraction(1, 2, '-');
assertTrue(result.equals(test.add(add)));
}
@Test
public void testAddNegativePositive() {
MyFraction test = new MyFraction(1, 4, '-');
MyFraction add = new MyFraction(3, 4, '+');
MyFraction result = new MyFraction(1, 2, '+');
assertTrue(result.equals(test.add(add)));
}
@Test
public void testAddDoubleNegative() {
MyFraction test = new MyFraction(1, 4, '-');
MyFraction add = new MyFraction(3, 4, '-');
MyFraction result = new MyFraction(1, 1, '-');
assertTrue(result.equals(test.add(add)));
}
@Test
public void testSubtractDoublePositive() {
MyFraction test = new MyFraction(1, 5, '+');
MyFraction subtract = new MyFraction(3, 5, '+');
MyFraction result = new MyFraction(2, 5, '-');
assertTrue(result.equals(test.subtract(subtract)));
}
@Test
public void testSubtractPositiveNegative() {
MyFraction test = new MyFraction(1, 5, '+');
MyFraction subtract = new MyFraction(3, 5, '-');
MyFraction result = new MyFraction(4, 5, '+');
assertTrue(result.equals(test.subtract(subtract)));
}
@Test
public void testSubtractNegativePositive() {
MyFraction test = new MyFraction(1, 5, '-');
MyFraction subtract = new MyFraction(3, 5, '+');
MyFraction result = new MyFraction(4, 5, '-');
assertTrue(result.equals(test.subtract(subtract)));
}
@Test
public void testSubtractDoubleNegative() {
MyFraction test = new MyFraction(1, 5, '-');
MyFraction subtract = new MyFraction(3, 5, '-');
MyFraction result = new MyFraction(2, 5, '+');
assertTrue(result.equals(test.subtract(subtract)));
}
@Test
public void testMultiplyDoublePositive() {
MyFraction test = new MyFraction(5, 5, '+');
MyFraction multiply = new MyFraction(1, 5, '+');
MyFraction result = new MyFraction(1, 5, '+');
assertTrue(result.equals(test.multiply(multiply)));
}
@Test
public void testMultiplyDoubleNegative() {
MyFraction test = new MyFraction(5, 5, '-');
MyFraction multiply = new MyFraction(1, 5, '-');
MyFraction result = new MyFraction(1, 5, '+');
assertTrue(result.equals(test.multiply(multiply)));
}
@Test
public void testMultiplyPositiveNegative() {
MyFraction test = new MyFraction(5, 5, '+');
MyFraction multiply = new MyFraction(1, 5, '-');
MyFraction result = new MyFraction(1, 5, '-');
assertTrue(result.equals(test.multiply(multiply)));
}
@Test
public void testMultiplyNegativePositive() {
MyFraction test = new MyFraction(5, 5, '-');
MyFraction multiply = new MyFraction(1, 5, '+');
MyFraction result = new MyFraction(1, 5, '-');
assertTrue(result.equals(test.multiply(multiply)));
}
@Test
public void testDivideDoublePositive() {
MyFraction test = new MyFraction(2, 3, '+');
MyFraction divide = new MyFraction(3, 1, '+');
MyFraction result = new MyFraction(2, 9, '+');
assertTrue(result.equals(test.divide(divide)));
}
@Test
public void testDivideDoubleNegative() {
MyFraction test = new MyFraction(2, 3, '-');
MyFraction divide = new MyFraction(3, 1, '-');
MyFraction result = new MyFraction(2, 9, '+');
assertTrue(result.equals(test.divide(divide)));
}
@Test
public void testDividePositiveNegative() {
MyFraction test = new MyFraction(2, 3, '+');
MyFraction divide = new MyFraction(3, 1, '-');
MyFraction result = new MyFraction(2, 9, '-');
assertTrue(result.equals(test.divide(divide)));
}
@Test
public void testDivideNegativePositive() {
MyFraction test = new MyFraction(2, 3, '-');
MyFraction divide = new MyFraction(3, 1, '+');
MyFraction result = new MyFraction(2, 9, '-');
assertTrue(result.equals(test.divide(divide)));
}
@Test
public void testToString() {
MyFraction test = new MyFraction( 3 , 10 , '+' );
assertNotNull( test.toString() );
}
}

74
CS2012 Lab 8/.gitignore vendored Executable file
View File

@ -0,0 +1,74 @@
fmframework/src/sarsoo/fmframework/net/Key.java
# Directories #
/build/
/bin/
target/
# OS Files #
.DS_Store
*.class
# Package Files #
*.jar
*.war
*.ear
*.db
######################
# Windows
######################
# Windows image file caches
Thumbs.db
# Folder config file
Desktop.ini
######################
# OSX
######################
.DS_Store
.svn
# Thumbnails
._*
# Files that might appear on external disk
.Spotlight-V100
.Trashes
######################
# Eclipse
######################
*.pydevproject
.project
.metadata
bin/**
tmp/**
tmp/**/*
*.tmp
*.bak
*.swp
*~.nib
local.properties
.classpath
.settings/
.loadpath
/src/main/resources/rebel.xml
# External tool builders
.externalToolBuilders/
# Locally stored "Eclipse launch configurations"
*.launch
# CDT-specific
.cproject
# PDT-specific
.buildpath

View File

@ -0,0 +1,31 @@
package fx;
import javafx.application.Application;
import javafx.stage.Stage;
import logic.StreetMap;
import javafx.scene.Scene;
public class BullRun extends Application {
@Override
public void start(Stage stage) {
stage.setTitle("bull run");
StreetMap map = new StreetMap(6, 2, 7, 22);
map.randomise();
MazeGUIPane maze = new MazeGUIPane(map);
maze.updateGUI();
Scene scene = new Scene(maze, 600, 700);
stage.setResizable(false);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}

View File

@ -0,0 +1,237 @@
package fx;
import javafx.scene.layout.*;
import logic.Bull;
import logic.Coordinate;
import logic.StreetMap;
import javafx.scene.control.Label;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.control.Button;
import javafx.event.*;
public class MazeGUIPane extends BorderPane {
private StreetMap map;
private Label[][] labels = new Label[27][27];
// private Coordinate player = new Coordinate(1, 1);
public MazeGUIPane(final StreetMap map) {
super();
getStylesheets().add("styles/style.css");
this.map = map;
HBox title = new HBox();
title.getStyleClass().add("box");
HBox bottom = new HBox();
bottom.getStyleClass().add("box");
GridPane grid = new GridPane();
grid.getStyleClass().add("grid");
Label titleText = new Label("The Bull Run");
titleText.getStyleClass().add("titletext");
title.getChildren().add(titleText);
Button random = new Button();
random.setText("Start");
random.getStyleClass().add("startbutton");
bottom.getChildren().add(random);
random.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<Event>() {
@Override
public void handle(Event event) {
map.randomise();
updateGUI();
// map.print();
}
});
int row, column;
for (row = 0; row < 27; row++) {
for (column = 0; column < 27; column++) {
Label label = new Label(" ");
label.setMinWidth(20);
label.setMinHeight(20);
label.getStyleClass().add("wall");
labels[row][column] = label;
final Coordinate coord = map.getCoordinate(row, column);
// coord.setLabel(label);
int coordCol = coord.getColumn();
int coordRow = coord.getRow();
if (coordCol > 0 && coordCol < 26) {
if (coordRow > 0 && coordRow < 26) {
label.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<Event>() {
@Override
public void handle(Event event) {
char state = coord.getState();
if (state == 'W') {
coord.setState(' ');
}
if (state == ' ') {
coord.setState('W');
}
updateGUI();
}
});
}
}
grid.add(label, column, row);
}
}
setCenter(grid);
setTop(title);
setBottom(bottom);
this.setEventHandler(KeyEvent.ANY, new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent key) {
if (key.getCode() == KeyCode.R) {
map.randomise();
updateGUI();
}
if (!(map.isDead() || map.isWon())) {
// map.isBlocked();
if (key.getCode() == KeyCode.DOWN) {
Coordinate player = map.getPlayer();
if (map.validMove(player.getRow() + 1, player.getColumn())) {
map.movePlayerDown();
map.isBlocked();
// updateGUI();
}
}
if (key.getCode() == KeyCode.UP) {
Coordinate player = map.getPlayer();
if (map.validMove(player.getRow() - 1, player.getColumn())) {
map.movePlayerUp();
map.isBlocked();
// updateGUI();
}
}
if (key.getCode() == KeyCode.LEFT) {
Coordinate player = map.getPlayer();
if (map.validMove(player.getRow(), player.getColumn() - 1)) {
map.movePlayerLeft();
map.isBlocked();
// updateGUI();
}
}
if (key.getCode() == KeyCode.RIGHT) {
Coordinate player = map.getPlayer();
if (map.validMove(player.getRow(), player.getColumn() + 1)) {
map.movePlayerRight();
map.isBlocked();
// updateGUI();
}
}
}
updateGUI();
}
});
}
public void updateGUI() {
Label label;
Coordinate coordinate;
int row, column;
for (row = 0; row < 27; row++) {
for (column = 0; column < 27; column++) {
coordinate = map.getCoordinate(row, column);
label = labels[row][column];
// System.out.println(coordinate.getState());
label.getStyleClass().clear();
switch (coordinate.getState()) {
case ' ':
label.getStyleClass().add("street");
break;
case 'W':
label.getStyleClass().add("wall");
break;
case 'S':
label.getStyleClass().add("start");
break;
case 'E':
label.getStyleClass().add("exit");
break;
// case 'P':
// label.getStyleClass().add("player");
}
}
}
Coordinate player = map.getPlayer();
Label playerLabel = labels[player.getRow()][player.getColumn()];
Bull[] bulls = map.getBulls();
for (Bull bull : bulls) {
Coordinate bullCoord = bull.getLocation();
Label bullLabel = labels[bullCoord.getRow()][bullCoord.getColumn()];
bullLabel.getStyleClass().clear();
bullLabel.getStyleClass().add("bull");
}
playerLabel.getStyleClass().clear();
if (map.isDead())
playerLabel.getStyleClass().add("dead");
else if (map.isWon())
playerLabel.getStyleClass().add("won");
else
playerLabel.getStyleClass().add("player");
// map.getCoordinate(0, 1).getLabel().setText("S");
// map.getCoordinate(26, 25).getLabel().setText("E");
labels[0][1].setText("S");
labels[26][25].setText("E");
}
public Label[][] getLabels() {
return labels;
}
}

248
CS2012 Lab 8/src/logic/Bull.java Executable file
View File

@ -0,0 +1,248 @@
package logic;
import java.util.Random;
public class Bull {
private Coordinate location;
private Coordinate lastSeen;
public Bull() {
this.setLocation(new Coordinate(1, 1));
}
public Coordinate getLocation() {
return location;
}
public void setLocation(Coordinate location) {
this.location = location;
}
public void move(Coordinate player, StreetMap map) {
// location = new Coordinate(2,2);
boolean see = canSee(player, map);
System.out.println("canSee: " + see);
if (see == true && (map.getTurn() > map.getHeadstart() + 1)) {
lastSeen = new Coordinate(player.getRow(), player.getColumn());
System.out.println(lastSeen);
}
if (lastSeen != null) {
System.out.println("MOVE");
if (location.getRow() == lastSeen.getRow()) {
System.out.println("Same Row");
if (location.getColumn() < lastSeen.getColumn()) {
System.out.println("west player");
if (map.validMove(location.getRow(), location.getColumn() + 1)) {
System.out.println("valid");
location.setColumn(location.getColumn() + 1);
System.out.println("Move east");
} else {
moveRandom(map);
}
}
else {
System.out.println("east player");
if (map.validMove(location.getRow(), location.getColumn() - 1)) {
System.out.println("valid");
location.setColumn(location.getColumn() - 1);
System.out.println("Move north");
} else {
moveRandom(map);
}
}
} else if (location.getColumn() == lastSeen.getColumn()) {
System.out.println("Same Column");
if (location.getRow() < lastSeen.getRow()) {
if (map.validMove(location.getRow() + 1, location.getColumn())) {
System.out.println("valid");
location.setRow(location.getRow() + 1);
System.out.println("Move south");
} else {
moveRandom(map);
}
}
else {
if (map.validMove(location.getRow() - 1, location.getColumn())) {
System.out.println("valid");
location.setRow(location.getRow() - 1);
System.out.println("Move north");
} else {
moveRandom(map);
}
}
} else {
moveRandom(map);
}
if (location.equals(lastSeen))
lastSeen = null;
} else {
moveRandom(map);
}
if (location.equals(player)) {
map.setIsDead(true);
}
see = canSee(player, map);
if (see == true && (map.getTurn() > map.getHeadstart() + 1)) {
lastSeen = new Coordinate(player.getRow(), player.getColumn());
System.out.println(lastSeen);
}
}
public void moveRandom(StreetMap map) {
boolean moveMade = false;
System.out.println("Move random");
Random rand = new Random();
int counter = 0;
do {
int random = rand.nextInt(4) + 1;
System.out.println("random: " + random);
switch (random) {
// NORTH
case (1):
if (map.validMove(location.getRow() - 1, location.getColumn())) {
location.setRow(location.getRow() - 1);
moveMade = true;
}
counter++;
break;
// EAST
case (2):
if (map.validMove(location.getRow(), location.getColumn() + 1)) {
location.setColumn(location.getColumn() + 1);
moveMade = true;
}
counter++;
break;
// SOUTH
case (3):
if (map.validMove(location.getRow() + 1, location.getColumn())) {
location.setRow(location.getRow() + 1);
moveMade = true;
}
counter++;
break;
// WEST
case (4):
if (map.validMove(location.getRow(), location.getColumn() - 1)) {
location.setColumn(location.getColumn() - 1);
moveMade = true;
}
counter++;
break;
default:
System.err.println("Invalid random number");
}
} while ((moveMade == false) && (counter < 5));
}
public boolean canSee(Coordinate player, StreetMap map) {
boolean canSee = false;
// SAME ROW
if (location.getRow() == player.getRow()) {
canSee = true;
int distance = Math.abs(player.getColumn() - location.getColumn()) - 1;
boolean wall = false;
int counter;
Coordinate coord;
// BULL ABOVE PLAYER
if (location.getColumn() < player.getColumn()) {
for (counter = location.getColumn() + 1; counter < distance; counter++) {
coord = map.getCoordinate(location.getRow(), counter);
if (coord.getState() == 'W') {
wall = true;
}
}
}
// PLAYER ABOVE BULL
else {
for (counter = player.getColumn() + 1; counter < distance; counter++) {
coord = map.getCoordinate(location.getRow(), counter);
if (coord.getState() == 'W') {
wall = true;
}
}
}
if (wall == true)
canSee = false;
}
// SAME COLUMN
else if (location.getColumn() == player.getColumn()) {
canSee = true;
int distance = Math.abs(player.getRow() - location.getRow()) - 1;
boolean wall = false;
int counter;
Coordinate coord;
// BULL ABOVE PLAYER
if (location.getRow() < player.getRow()) {
for (counter = location.getRow() + 1; counter < distance; counter++) {
coord = map.getCoordinate(counter, location.getColumn());
if (coord.getState() == 'W') {
wall = true;
}
}
}
// PLAYER ABOVE BULL
else {
for (counter = player.getRow() + 1; counter < distance; counter++) {
coord = map.getCoordinate(counter, location.getColumn());
if (coord.getState() == 'W') {
wall = true;
}
}
}
if (wall == true)
canSee = false;
}
return canSee;
}
}

View File

@ -0,0 +1,79 @@
package logic;
public class Coordinate {
private int row;
private int column;
private char state;
// private Label label;
public Coordinate(int row, int column, char state) {
this.row = row;
this.column = column;
this.state = state;
}
public Coordinate(int row, int column) {
this.row = row;
this.column = column;
}
@Override
public boolean equals(Object obj) {
if(obj.getClass() != this.getClass())
return false;
Coordinate coord = (Coordinate) obj;
if(column == coord.getColumn() && row == coord.getRow()) {
return true;
}
return false;
}
public String toString() {
return "(" + row + ", " + column + ") " + state;
}
public int getRow() {
return row;
}
public void setRow(int row) {
this.row = row;
}
public int getColumn() {
return column;
}
public void setColumn(int column) {
this.column = column;
}
public char getState() {
return state;
}
public void setState(char state) {
this.state = state;
}
public void increaseRow() {
row++;
}
public void decreaseRow() {
row--;
}
public void increaseCol() {
column++;
}
public void decreaseCol() {
column--;
}
// public Label getLabel() {
// return label;
// }
//
// public void setLabel(Label label) {
// this.label = label;
// }
}

View File

@ -0,0 +1,239 @@
package logic;
import java.util.Random;
public class StreetMap {
private Coordinate[][] map = new Coordinate[27][27];
private Coordinate player = new Coordinate(1, 1);
private Bull[] bulls;
private boolean isDead = false;
private int turn = 0;
private int bullNumber;
private int turnNumber;
private int headstart;
private int wallPercent;
public int getTurn() {
return turn;
}
public int getHeadstart() {
return headstart;
}
public StreetMap(int bullNumber, int turnNumber, int headstart, int wallPercent) {
this.bullNumber = bullNumber;
this.turnNumber = turnNumber;
this.headstart = headstart;
this.wallPercent = wallPercent;
int row, column;
for (row = 0; row < 27; row++) {
for (column = 0; column < 27; column++) {
Coordinate coord = new Coordinate(row, column, 'W');
map[row][column] = coord;
}
}
getCoordinate(0, 1).setState('S');
getCoordinate(26, 25).setState('E');
randomise();
// bulls = new Bull[bullNumber];
// int counter;
// for (counter = 0; counter < bullNumber; counter++) {
// bulls[counter] = new Bull();
// }
}
public void randomise() {
Random random = new Random();
int row, column;
for (row = 1; row < 26; row++) {
for (column = 1; column < 26; column++) {
int rand = random.nextInt(100) + 1;
if (rand > wallPercent) {
getCoordinate(row, column).setState(' ');
} else {
getCoordinate(row, column).setState('W');
}
}
}
for (row = 1; row < 5; row++) {
for (column = 1; column < 5; column++) {
getCoordinate(row, column).setState(' ');
}
}
for (row = 24; row < 26; row++) {
for (column = 24; column < 26; column++) {
getCoordinate(row, column).setState(' ');
}
}
getCoordinate(3, 3).setState('W');
// int counter;
// for (counter = 0; counter < bullNumber; counter++) {
//// bulls[counter] = new Bull();
// }
bulls = new Bull[bullNumber];
int counter;
for (counter = 0; counter < bullNumber; counter++) {
bulls[counter] = new Bull();
}
player.setColumn(1);
player.setRow(1);
isDead = false;
turn = 0;
}
public boolean validMove(int row, int column) {
if (row == 0)
return false;
if (column == 0)
return false;
if (column == 26)
return false;
if (row == 26) {
if (column == 25)
return true;
return false;
}
Coordinate coord = map[row][column];
char state = coord.getState();
if (state == 'W') {
return false;
}
if (turn > headstart + 1) {
for (Bull bull : bulls) {
Coordinate bullCoord = bull.getLocation();
if (bullCoord.getRow() == row)
if (bullCoord.getColumn() == column)
return false;
}
}
return true;
}
public boolean isWon() {
if (player.equals(new Coordinate(26, 25)))
return true;
return false;
}
public boolean isDead() {
return isDead;
}
public void setIsDead(boolean b) {
this.isDead = b;
}
public void movePlayerUp() {
player.decreaseRow();
if (++turn > headstart)
moveBulls();
}
public void movePlayerDown() {
player.increaseRow();
if (++turn > headstart)
moveBulls();
}
public void movePlayerLeft() {
player.decreaseCol();
if (++turn > headstart)
moveBulls();
}
public void movePlayerRight() {
player.increaseCol();
if (++turn > headstart)
moveBulls();
}
public void moveBulls() {
int counter;
for (Bull bull : bulls) {
for (counter = 0; counter < turnNumber; counter++) {
bull.move(player, this);
}
}
}
public Coordinate getCoordinate(int row, int column) {
return map[row][column];
}
public Coordinate[][] getMap() {
return map;
}
public void setCoordinateState(int row, int column, char state) {
getCoordinate(row, column).setState(state);
}
public void setMap(Coordinate[][] map) {
this.map = map;
}
public Coordinate getPlayer() {
return player;
}
public Bull[] getBulls() {
return bulls;
}
public void print() {
int row, column;
for (row = 0; row < 27; row++) {
for (column = 0; column < 27; column++) {
System.out.print(getCoordinate(row, column).getState());
if (column == 26)
System.out.println();
}
}
}
public void isBlocked() {
if (player.getRow() != 26) {
if (!validMove(player.getRow() - 1, player.getColumn())) {
if (!validMove(player.getRow() + 1, player.getColumn())) {
if (!validMove(player.getRow(), player.getColumn() - 1)) {
if (!validMove(player.getRow(), player.getColumn() + 1)) {
isDead = true;
}
}
}
}
}
}
}

View File

@ -0,0 +1,88 @@
.titletext{
-fx-alignment: center;
-fx-font-style: italic;
-fx-font-size: 500%;
}
.startbutton{
-fx-alignment: center;
}
.box{
-fx-alignment: center;
}
.grid{
-fx-alignment: center;
-fx-grid-lines-visible: true;
}
.start{
-fx-background-color: #4844ba;
-fx-alignment: center;
-fx-text-fill: #FFFFFF;
-fx-font-size: 110%;
}
.exit{
-fx-background-color: #4844ba;
-fx-alignment: center;
-fx-text-fill: #FFFFFF;
-fx-font-size: 110%;
}
.wall{
-fx-background-color: #470000;
}
.street{
-fx-background-color: #a0a0a0;
}
.player{
-fx-background-color: white;
-fx-alignment: center;
-fx-text-fill: #000000;
-fx-font-size: 110%;
}
.won{
-fx-background-color: gold;
-fx-alignment: center;
-fx-text-fill: #000000;
-fx-font-size: 110%;
}
.dead{
-fx-background-color: red;
-fx-alignment: center;
-fx-text-fill: #000000;
-fx-font-size: 110%;
}
.bull{
-fx-background-color: #fffa00;
}

View File

@ -0,0 +1,29 @@
package test;
import static org.junit.Assert.*;
import org.junit.Test;
import logic.Coordinate;
public class CoordinateTest {
@Test
public void testInit() {
Coordinate coord = new Coordinate(1,1,'W');
assertNotNull(coord);
}
// @Test
// public void testToString() {
// Coordinate coord = new Coordinate(1,2);
// assertEquals(coord.toString(), "(1, 2) ");
// }
@Test
public void testToStringWall() {
Coordinate coord = new Coordinate(1,2,'W');
assertEquals(coord.toString(), "(1, 2) W");
}
}

View File

@ -0,0 +1,33 @@
package test;
//import static org.junit.Assert.*;
import org.junit.Test;
import logic.StreetMap;
public class StreetMapTest {
// @Test
// public void test() {
// StreetMap map = new StreetMap();
//
// int row, column;
// for(row = 0; row < 27; row++) {
// for(column = 0; column < 27; column++) {
//
// System.out.println(map.getCoordinate(row, column));
//
// }
// }
// }
//
@Test
public void test() {
StreetMap map = new StreetMap(5, 1, 2, 30);
map.print();
// map.randomise();
// map.print();
}
}

58
CS2012 Quiz 10/.gitignore vendored Normal file
View File

@ -0,0 +1,58 @@
.metadata
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.settings/
.loadpath
.recommenders
# External tool builders
.externalToolBuilders/
# Locally stored "Eclipse launch configurations"
*.launch
# PyDev specific (Python IDE for Eclipse)
*.pydevproject
# CDT-specific (C/C++ Development Tooling)
.cproject
# CDT- autotools
.autotools
# Java annotation processor (APT)
.factorypath
# PDT-specific (PHP Development Tools)
.buildpath
# sbteclipse plugin
.target
# Tern plugin
.tern-project
# TeXlipse plugin
.texlipse
# STS (Spring Tool Suite)
.springBeans
# Code Recommenders
.recommenders/
# Annotation Processing
.apt_generated/
# Scala IDE specific (Scala & Java development for Eclipse)
.cache-main
.scala_dependencies
.worksheet
.classpath
.project

View File

@ -0,0 +1,27 @@
package clickcounter;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class ClickCounter extends Application{
@Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("../ui/clickfxml.fxml"));
Scene scene = new Scene(root, 800, 400);
scene.getStylesheets().add("ui/style.css");
stage.setTitle("Click Counter");
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}

View File

@ -0,0 +1,29 @@
package clickcounter;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.text.Text;
import javafx.scene.control.Button;
public class Controller {
@FXML
private Text results;
private int clicked = 0;
@FXML
protected void handleButtonClick(ActionEvent event) {
int num = 0;
Button button = (Button) event.getSource();
if(button.getText().equals("unclicked")) {
results.setText("Clicked: " + ++clicked);
button.setText("clicked");
}else {
results.setText("Clicked: " + --clicked);
button.setText("unclicked");
}
}
}

View File

@ -0,0 +1,129 @@
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.AnchorPane?>
<?import java.net.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.text.*?>
<GridPane fx:controller="clickcounter.Controller"
xmlns:fx="http://javafx.com/fxml" alignment="center" hgap="10" vgap="10" styleClass = "GridPane" >
<padding>
<Insets top="25" right="25" bottom="10" left="25" />
</padding>
<Text fx:id="results" text="Clicked: 0" GridPane.columnIndex="0" GridPane.rowIndex="0"
GridPane.columnSpan="10" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="1" GridPane.columnIndex = "0" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="1" GridPane.columnIndex = "1" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="1" GridPane.columnIndex = "2" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="1" GridPane.columnIndex = "3" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="1" GridPane.columnIndex = "4" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="1" GridPane.columnIndex = "5" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="1" GridPane.columnIndex = "6" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="1" GridPane.columnIndex = "7" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="1" GridPane.columnIndex = "8" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="1" GridPane.columnIndex = "9" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="2" GridPane.columnIndex = "0" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="2" GridPane.columnIndex = "1" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="2" GridPane.columnIndex = "2" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="2" GridPane.columnIndex = "3" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="2" GridPane.columnIndex = "4" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="2" GridPane.columnIndex = "5" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="2" GridPane.columnIndex = "6" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="2" GridPane.columnIndex = "7" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="2" GridPane.columnIndex = "8" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="2" GridPane.columnIndex = "9" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="3" GridPane.columnIndex = "0" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="3" GridPane.columnIndex = "1" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="3" GridPane.columnIndex = "2" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="3" GridPane.columnIndex = "3" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="3" GridPane.columnIndex = "4" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="3" GridPane.columnIndex = "5" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="3" GridPane.columnIndex = "6" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="3" GridPane.columnIndex = "7" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="3" GridPane.columnIndex = "8" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="3" GridPane.columnIndex = "9" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="4" GridPane.columnIndex = "0" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="4" GridPane.columnIndex = "1" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="4" GridPane.columnIndex = "2" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="4" GridPane.columnIndex = "3" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="4" GridPane.columnIndex = "4" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="4" GridPane.columnIndex = "5" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="4" GridPane.columnIndex = "6" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="4" GridPane.columnIndex = "7" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="4" GridPane.columnIndex = "8" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="4" GridPane.columnIndex = "9" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="5" GridPane.columnIndex = "0" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="5" GridPane.columnIndex = "1" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="5" GridPane.columnIndex = "2" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="5" GridPane.columnIndex = "3" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="5" GridPane.columnIndex = "4" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="5" GridPane.columnIndex = "5" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="5" GridPane.columnIndex = "6" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="5" GridPane.columnIndex = "7" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="5" GridPane.columnIndex = "8" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="5" GridPane.columnIndex = "9" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="6" GridPane.columnIndex = "0" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="6" GridPane.columnIndex = "1" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="6" GridPane.columnIndex = "2" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="6" GridPane.columnIndex = "3" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="6" GridPane.columnIndex = "4" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="6" GridPane.columnIndex = "5" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="6" GridPane.columnIndex = "6" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="6" GridPane.columnIndex = "7" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="6" GridPane.columnIndex = "8" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="6" GridPane.columnIndex = "9" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="7" GridPane.columnIndex = "0" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="7" GridPane.columnIndex = "1" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="7" GridPane.columnIndex = "2" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="7" GridPane.columnIndex = "3" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="7" GridPane.columnIndex = "4" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="7" GridPane.columnIndex = "5" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="7" GridPane.columnIndex = "6" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="7" GridPane.columnIndex = "7" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="7" GridPane.columnIndex = "8" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="7" GridPane.columnIndex = "9" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="8" GridPane.columnIndex = "0" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="8" GridPane.columnIndex = "1" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="8" GridPane.columnIndex = "2" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="8" GridPane.columnIndex = "3" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="8" GridPane.columnIndex = "4" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="8" GridPane.columnIndex = "5" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="8" GridPane.columnIndex = "6" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="8" GridPane.columnIndex = "7" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="8" GridPane.columnIndex = "8" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="8" GridPane.columnIndex = "9" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="9" GridPane.columnIndex = "0" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="9" GridPane.columnIndex = "1" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="9" GridPane.columnIndex = "2" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="9" GridPane.columnIndex = "3" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="9" GridPane.columnIndex = "4" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="9" GridPane.columnIndex = "5" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="9" GridPane.columnIndex = "6" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="9" GridPane.columnIndex = "7" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="9" GridPane.columnIndex = "8" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="9" GridPane.columnIndex = "9" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="10" GridPane.columnIndex = "0" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="10" GridPane.columnIndex = "1" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="10" GridPane.columnIndex = "2" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="10" GridPane.columnIndex = "3" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="10" GridPane.columnIndex = "4" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="10" GridPane.columnIndex = "5" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="10" GridPane.columnIndex = "6" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="10" GridPane.columnIndex = "7" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="10" GridPane.columnIndex = "8" GridPane.halignment="CENTER"/>
<Button onAction="#handleButtonClick" text="unclicked" GridPane.rowIndex="10" GridPane.columnIndex = "9" GridPane.halignment="CENTER"/>
</GridPane>

View File

@ -0,0 +1,4 @@
.GridPane{
}

58
CS2012 Quiz 11/.gitignore vendored Normal file
View File

@ -0,0 +1,58 @@
.metadata
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.settings/
.loadpath
.recommenders
# External tool builders
.externalToolBuilders/
# Locally stored "Eclipse launch configurations"
*.launch
# PyDev specific (Python IDE for Eclipse)
*.pydevproject
# CDT-specific (C/C++ Development Tooling)
.cproject
# CDT- autotools
.autotools
# Java annotation processor (APT)
.factorypath
# PDT-specific (PHP Development Tools)
.buildpath
# sbteclipse plugin
.target
# Tern plugin
.tern-project
# TeXlipse plugin
.texlipse
# STS (Spring Tool Suite)
.springBeans
# Code Recommenders
.recommenders/
# Annotation Processing
.apt_generated/
# Scala IDE specific (Scala & Java development for Eclipse)
.cache-main
.scala_dependencies
.worksheet
.classpath
.project

View File

@ -0,0 +1,13 @@
package monsterfight;
public class Drive {
public static void main(String[] args) {
MonsterAttack attack = new MonsterAttack();
attack.fight();
}
}

View File

@ -0,0 +1,37 @@
package monsterfight;
public class HeroMonster extends Monster {
private String weapon;
public HeroMonster(String name, double ferocity, String weapon) {
this.name = name.toUpperCase();
this.ferocity = ferocity;
this.weapon = weapon.toUpperCase();
}
@Override
public String toString() {
return "hero: " + name + " (" + ferocity + ") wielding: " + weapon;
}
@Override
public void attack(Monster m) {
double roll = r.nextDouble();
System.out.println(name + " attacks " + m.getName() + " with " + weapon);
if(roll < ferocity) {
m.expire();
System.out.println(m.getName() + " dies");
}
else {
System.out.println(m.getName() + " survives");
}
}
}

View File

@ -0,0 +1,26 @@
package monsterfight;
import java.util.Random;
public abstract class Monster {
protected Random r = new Random();
protected boolean alive = true;
protected String name;
protected double ferocity; // probability (0 through 1) chance that the monster will succeed in each
// attack.
public abstract void attack(Monster m); // implement this in the subclasses
public boolean isAlive() {
return alive;
}
public void expire() { // run when a monster dies
alive = false;
}
// plcheck
public String getName() {
return name;
}
}

View File

@ -0,0 +1,84 @@
package monsterfight;
import java.util.ArrayList;
import java.util.List;
public class MonsterAttack {
private int round;
public void fight() {
Monster godzilla = new HeroMonster("Godzilla", 0.7, "radioactive breath");
List<Monster> zombies = new ArrayList<Monster>();
int counter;
for (counter = 0; counter < 20; counter++) {
zombies.add(new Zombie());
}
fightRecursively(godzilla, zombies);
if(godzilla.isAlive()) {
System.out.println("the zombies were wiped out");
}else {
int alive = 0;
for(counter = 0; counter < zombies.size(); counter++)
if(zombies.get(counter).isAlive()) alive++;
System.out.println("Godzilla died, " + alive + " zombies rampage");
}
}
private void fightRecursively(Monster hero, List<Monster> zombies) {
if (hero.isAlive()) {
if (zombies.size() > 0) {
List<Monster> remainingZombies = new ArrayList<Monster>();
System.out.println("\t\t Round " + ++round);
int counter;
for (counter = 0; counter < zombies.size(); counter++) {
if (hero.isAlive()) {
Monster zombie = zombies.get(counter);
hero.attack(zombie);
if (zombie.isAlive()) {
zombie.attack(hero);
remainingZombies.add(zombie);
}
// else {
// zombie.attack(hero);
// }
// if(hero.isAlive() == false) {
// System.out.println();
// System.out.println();
// System.out.println(hero.getName() + " has died, " + remainingZombies.size() + " zombies rampage");
// }
System.out.println();
}
}
System.out.println();
System.out.println();
fightRecursively(hero, remainingZombies);
}
// else {
// System.out.println("the zombies were wiped out");
// }
}
}
}

View File

@ -0,0 +1,44 @@
package monsterfight;
public class Zombie extends Monster {
private static int population = 0;
private int number;
public Zombie() {
this.name = "ZOMBIE #" + ++population;
this.number = population;
this.ferocity = 0.1;
}
@Override
public String toString() {
return name + " (" + ferocity + ")";
}
@Override
public void attack(Monster m) {
double roll = r.nextDouble();
System.out.println(name + " tries to eat " + m.getName() + "'s brains");
if (roll < ferocity) {
m.expire();
System.out.println(m.getName() + " dies");
} else {
System.out.println(m.getName() + " survives");
}
}
public int getNumber() {
return number;
}
}

58
CS2012 Quiz 5/.gitignore vendored Normal file
View File

@ -0,0 +1,58 @@
.metadata
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.settings/
.loadpath
.recommenders
# External tool builders
.externalToolBuilders/
# Locally stored "Eclipse launch configurations"
*.launch
# PyDev specific (Python IDE for Eclipse)
*.pydevproject
# CDT-specific (C/C++ Development Tooling)
.cproject
# CDT- autotools
.autotools
# Java annotation processor (APT)
.factorypath
# PDT-specific (PHP Development Tools)
.buildpath
# sbteclipse plugin
.target
# Tern plugin
.tern-project
# TeXlipse plugin
.texlipse
# STS (Spring Tool Suite)
.springBeans
# Code Recommenders
.recommenders/
# Annotation Processing
.apt_generated/
# Scala IDE specific (Scala & Java development for Eclipse)
.cache-main
.scala_dependencies
.worksheet
.classpath
.project

View File

@ -0,0 +1,23 @@
import java.util.ArrayList;
public class CourseRoll {
private ArrayList<Student> students = new ArrayList<Student>();
private int nextCin = 1;
public void offerClass(){
RandomArrayGenerator gen = new RandomArrayGenerator();
double[] data = gen.getGaussianData(3, 0.75, 30, 2, 4);
int counter;
Student student;
for(counter = 0; counter < 30; counter++) {
student = new Student(nextCin++, data[counter]);
students.add(student);
}
for(counter = 0; counter < 30; counter++) {
System.out.println(students.get(counter));
}
}
}

10
CS2012 Quiz 5/src/Driver.java Executable file
View File

@ -0,0 +1,10 @@
public class Driver {
public static void main(String[] args) {
CourseRoll roll = new CourseRoll();
roll.offerClass();
}
}

View File

@ -0,0 +1,33 @@
import java.util.Random;
public class RandomArrayGenerator {
private double[] nums;
public double[] getGaussianData(double mean, double std, int count, double min, double max) {
Random r = new Random();
nums = new double[count];
double randDoub;
for (int counter = 0; counter < nums.length; counter++){
randDoub = r.nextGaussian() * std + mean;
// it's pretty hard to set limits for the values in a good way, so here is a hacky way.
if(randDoub > max) randDoub = max;
if(randDoub < min) randDoub = min;
nums[counter] = randDoub;
}
return nums;
}
public double[] getLinearData(int count, double min, double max) {
// it would be better to make sure max < min first, but I am not implementing this in this example
Random r = new Random();
nums = new double[count];
double randDoub;
for (int counter = 0; counter < nums.length; counter++){
randDoub = r.nextDouble() * (max - min) + min;
nums[counter] = randDoub;
}
return nums;
}
}

14
CS2012 Quiz 5/src/Student.java Executable file
View File

@ -0,0 +1,14 @@
public class Student {
private int cin;
private double gpa;
public Student(int cin, double gpa) {
super();
this.cin = cin;
this.gpa = gpa;
}
public String toString() {
return String.format("Student # %d has GPA of %.2f", cin, gpa);
}
}

58
CS2012 Quiz 6/.gitignore vendored Normal file
View File

@ -0,0 +1,58 @@
.metadata
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.settings/
.loadpath
.recommenders
# External tool builders
.externalToolBuilders/
# Locally stored "Eclipse launch configurations"
*.launch
# PyDev specific (Python IDE for Eclipse)
*.pydevproject
# CDT-specific (C/C++ Development Tooling)
.cproject
# CDT- autotools
.autotools
# Java annotation processor (APT)
.factorypath
# PDT-specific (PHP Development Tools)
.buildpath
# sbteclipse plugin
.target
# Tern plugin
.tern-project
# TeXlipse plugin
.texlipse
# STS (Spring Tool Suite)
.springBeans
# Code Recommenders
.recommenders/
# Annotation Processing
.apt_generated/
# Scala IDE specific (Scala & Java development for Eclipse)
.cache-main
.scala_dependencies
.worksheet
.classpath
.project

25
CS2012 Quiz 6/src/Asylum.java Executable file
View File

@ -0,0 +1,25 @@
public class Asylum extends Building{
private String name;
public Asylum(double size, boolean haunted, String name) {
this.size = size;
this.isHaunted = haunted;
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public void explore() {
System.out.println("The asylum " + name + " measures " + size + " sq metres");
if(isHaunted) System.out.println("A Ghost!");
}
}

22
CS2012 Quiz 6/src/Building.java Executable file
View File

@ -0,0 +1,22 @@
public abstract class Building {
protected double size;
protected boolean isHaunted;
public abstract void explore();
public double getSize() {
return size;
}
public void setSize(double size) {
this.size = size;
}
public boolean isHaunted() {
return isHaunted;
}
public void setHaunted(boolean isHaunted) {
this.isHaunted = isHaunted;
}
}

18
CS2012 Quiz 6/src/Driver.java Executable file
View File

@ -0,0 +1,18 @@
public class Driver {
public static void main(String[] args) {
Street street = new Street("York Way");
street.addHouse(15, false, "Blue Door");
street.addHouse(13.5, true, "Red Door");
street.addAsylum(20, true, "First Asylum");
street.addAsylum(20, false, "New Asylum");
street.addHouse(15, false, "Lack of Doors");
street.addHouse(10, true, "Broken Window");
street.addHouse(15, false, "Red Postbox");
street.stroll();
}
}

26
CS2012 Quiz 6/src/House.java Executable file
View File

@ -0,0 +1,26 @@
public class House extends Building{
private String feature;
public House(double size, boolean haunted, String feature) {
this.size = size;
this.isHaunted = haunted;
this.feature = feature;
}
public String getFeature() {
return feature;
}
public void setFeature(String feature) {
this.feature = feature;
}
@Override
public void explore() {
System.out.println("This house measures " + size + " sq metres with a(n) " + feature);
if(isHaunted) System.out.println("A Ghost!");
}
}

56
CS2012 Quiz 6/src/Street.java Executable file
View File

@ -0,0 +1,56 @@
import java.util.ArrayList;
public class Street {
private String name;
private ArrayList<Building> buildings = new ArrayList<Building>();
public Street(String name) {
this.setName(name);
}
public void addHouse(double size, boolean haunted, String feature) {
buildings.add(new House(size, haunted, feature));
}
public void addAsylum(double size, boolean haunted, String name) {
buildings.add(new Asylum(size, haunted, name));
}
public void stroll() {
System.out.println("Let's go down " + this.getName());
int counter;
Building currentBuilding;
for(counter = 0; counter < buildings.size(); counter++) {
currentBuilding = buildings.get(counter);
currentBuilding.explore();
}
System.out.println(this.getHaunted() + " of the buildings on " + this.getName() + " are haunted");
}
public int getHaunted() {
int haunted = 0;
int counter;
Building building;
for(counter = 0; counter < buildings.size(); counter++) {
building = buildings.get(counter);
if(building.isHaunted()) haunted++;
}
return haunted;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

58
CS2012 Quiz 8/.gitignore vendored Normal file
View File

@ -0,0 +1,58 @@
.metadata
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.settings/
.loadpath
.recommenders
# External tool builders
.externalToolBuilders/
# Locally stored "Eclipse launch configurations"
*.launch
# PyDev specific (Python IDE for Eclipse)
*.pydevproject
# CDT-specific (C/C++ Development Tooling)
.cproject
# CDT- autotools
.autotools
# Java annotation processor (APT)
.factorypath
# PDT-specific (PHP Development Tools)
.buildpath
# sbteclipse plugin
.target
# Tern plugin
.tern-project
# TeXlipse plugin
.texlipse
# STS (Spring Tool Suite)
.springBeans
# Code Recommenders
.recommenders/
# Annotation Processing
.apt_generated/
# Scala IDE specific (Scala & Java development for Eclipse)
.cache-main
.scala_dependencies
.worksheet
.classpath
.project

View File

@ -0,0 +1,20 @@
package conversion;
public class EnglishToMetricConverter implements ScaleConverter{
@Override
public double convertTemperature(double tempIn) {
return (tempIn - 32) * 5/9;
}
@Override
public double convertDistance(double distanceIn) {
return distanceIn * 1.609;
}
@Override
public double convertWeight(double weightIn) {
return weightIn / 2.2;
}
}

View File

@ -0,0 +1,20 @@
package conversion;
public class MetricToEnglishConverter implements ScaleConverter{
@Override
public double convertTemperature(double tempIn) {
return (tempIn * 9/5) + 32;
}
@Override
public double convertDistance(double distanceIn) {
return distanceIn / 1.609;
}
@Override
public double convertWeight(double weightIn) {
return weightIn * 2.2;
}
}

View File

@ -0,0 +1,9 @@
package conversion;
public interface ScaleConverter {
public double convertTemperature(double tempIn);
public double convertDistance(double distanceIn);
public double convertWeight(double weightIn);
}

View File

@ -0,0 +1,82 @@
package test;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import conversion.EnglishToMetricConverter;
class EnglishToMetricConverterTester {
@Test
public void testFreezingConversion() {
EnglishToMetricConverter e = new EnglishToMetricConverter();
final double freezingF = 32.0;
final double freezingC = 0.0;
assertEquals(e.convertTemperature(freezingF), freezingC, 0.0001);
}
@Test
public void testBoilingConversion() {
EnglishToMetricConverter e = new EnglishToMetricConverter();
final double boilingF = 212.0;
final double boilingC = 100.0;
assertEquals(e.convertTemperature(boilingF), boilingC, 0.0001);
}
@Test
public void test40Conversion() {
EnglishToMetricConverter e = new EnglishToMetricConverter();
final double boilingF = -40;
final double boilingC = -40;
assertEquals(e.convertTemperature(boilingF), boilingC, 0.0001);
}
@Test
public void test1MileConversion() {
EnglishToMetricConverter e = new EnglishToMetricConverter();
final double mile = 1;
final double km = 1.609;
assertEquals(e.convertDistance(mile), km, 0.0001);
}
@Test
public void test1KmConversion() {
EnglishToMetricConverter e = new EnglishToMetricConverter();
final double mile = 0.609;
final double km = 0.98;
assertEquals(e.convertDistance(mile), km, 0.001);
}
@Test
public void test8MileConversion() {
EnglishToMetricConverter e = new EnglishToMetricConverter();
final double mile = 8;
final double km = 12.8748;
assertEquals(e.convertDistance(mile), km, 0.01);
}
@Test
public void test2LbConversion() {
EnglishToMetricConverter e = new EnglishToMetricConverter();
final double lb = 2.2;
final double kg = 1;
assertEquals(e.convertWeight(lb), kg, 0.0001);
}
@Test
public void test1LbConversion() {
EnglishToMetricConverter e = new EnglishToMetricConverter();
final double lb = 1;
final double kg = 0.453592;
assertEquals(e.convertWeight(lb), kg, 0.01);
}
@Test
public void test200LbConversion() {
EnglishToMetricConverter e = new EnglishToMetricConverter();
final double lb = 200;
final double kg = 90.9090;
assertEquals(e.convertWeight(lb), kg, 0.0001);
}
}

58
CS2012 Sample Final/.gitignore vendored Normal file
View File

@ -0,0 +1,58 @@
.metadata
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.settings/
.loadpath
.recommenders
# External tool builders
.externalToolBuilders/
# Locally stored "Eclipse launch configurations"
*.launch
# PyDev specific (Python IDE for Eclipse)
*.pydevproject
# CDT-specific (C/C++ Development Tooling)
.cproject
# CDT- autotools
.autotools
# Java annotation processor (APT)
.factorypath
# PDT-specific (PHP Development Tools)
.buildpath
# sbteclipse plugin
.target
# Tern plugin
.tern-project
# TeXlipse plugin
.texlipse
# STS (Spring Tool Suite)
.springBeans
# Code Recommenders
.recommenders/
# Annotation Processing
.apt_generated/
# Scala IDE specific (Scala & Java development for Eclipse)
.cache-main
.scala_dependencies
.worksheet
.classpath
.project

16
CS2012 Sample Final/partII.java Executable file
View File

@ -0,0 +1,16 @@
public double getPercentUnderBed(List<Monster> monsters){
int totalUnderBed = 0;
int counter;
for(counter = 0; counter < monsters.size(); counter++){
if(monsters.get(counter).isUnderBed()){
totalUnderBed++;
}
}
return (double)totalUnderBed * 100 / (double) monsters.size();
}

View File

@ -0,0 +1,76 @@
package finalexam;
import java.util.Random;
public abstract class Animal {
Random r = new Random();
double health = 1; // if health reaches 0, the Animal dies
double accuracy; // probability (0 to 1) that an attack by this Animal hits its target.
double power; // amount of damage (0 to 1) done by a successful attack by this Animal
String name;
public boolean isAlive() {
// write code here to return true if the Animal's health is a positive number,
// otherwise false
if(health > 0) {
return true;
}else {
return false;
}
}
// receiveInjury() is run when this animal is the victim of a successful attack
public void receiveInjury(double d) {
// write code here to do the following:
// reduce this Animal's health by d, the parameter
// print a message about the damage
// print a message if the Animal is now dead
// otherwise, print a message showing the Animal's current health
if(d > health) {
health = 0;
}else {
health -= d;
}
System.out.println(name + String.format(" took %.2f of damage", d));
if(!isAlive()) {
System.out.println(name + " died");
}else {
System.out.println(name + String.format(" has %.2f health remaining", health));
}
}
public void attack(Animal target) {
// write code here to do the following:
// print a message indicating whom this Animal is attacking (name of the other
// Animal)
// get a random double between 0 and 1
// if the random double is less than accuracy, the attack succeeds. In that
// case,
// call receiveInjury(power) on target. The argument is *this* Animal's power.
// otherwise, the attack fails. Print a message indicating that the attack
// missed.
System.out.println(name + " attacks " + target.getName());
double roll = r.nextDouble();
if(roll < accuracy) {
System.out.println("the attack lands!");
target.receiveInjury(power);
}else {
System.out.println("the attack misses");
}
}
// code a getName() here
public String getName() {
return name;
}
}

View File

@ -0,0 +1,19 @@
package finalexam;
public class DuckSizedHorse extends Animal{
public DuckSizedHorse(String name, double rain) {
this.name = name;
this.accuracy = 0.1;
this.power = 0.1/rain;
}
@Override
public String toString() {
return name + String.format(" is a duck sized horse of health: %.2f, accuracy: %.2f, power: %.2f", health, accuracy, power);
}
}

View File

@ -0,0 +1,47 @@
package finalexam;
import java.util.Random;
public class Fight {
public static void main(String[] args) {
Random rand = new Random();
double rain = rand.nextDouble();
double wind = rand.nextDouble();
DuckSizedHorse horse = new DuckSizedHorse("biff", rain);
HorseSizedDuck duck = new HorseSizedDuck("eric", wind);
System.out.println(horse);
System.out.println(duck);
System.out.println();
System.out.println(String.format("fight starts, wind: %.2f rain: %.2f", wind, rain));
fightRecursively(horse, duck);
System.out.println();
if(horse.isAlive()) {
System.out.println(horse.getName() + " wins");
}else {
System.out.println(duck.getName() + " wins");
}
}
public static void fightRecursively(Animal one, Animal two) {
System.out.println();
if (one.isAlive() && two.isAlive()) {
one.attack(two);
if(two.isAlive()) {
two.attack(one);
fightRecursively(one, two);
}
}
}
}

View File

@ -0,0 +1,18 @@
package finalexam;
public class HorseSizedDuck extends Animal{
public HorseSizedDuck(String name, double wind) {
this.name = name;
this.power = 0.1;
this.accuracy = 0.1 / wind;
}
@Override
public String toString() {
return name + String.format(" is a horse sized duck of health: %.2f, accuracy: %.2f, power: %.2f", health, accuracy, power);
}
}

58
CS2012 Sample Midterm/.gitignore vendored Normal file
View File

@ -0,0 +1,58 @@
.metadata
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.settings/
.loadpath
.recommenders
# External tool builders
.externalToolBuilders/
# Locally stored "Eclipse launch configurations"
*.launch
# PyDev specific (Python IDE for Eclipse)
*.pydevproject
# CDT-specific (C/C++ Development Tooling)
.cproject
# CDT- autotools
.autotools
# Java annotation processor (APT)
.factorypath
# PDT-specific (PHP Development Tools)
.buildpath
# sbteclipse plugin
.target
# Tern plugin
.tern-project
# TeXlipse plugin
.texlipse
# STS (Spring Tool Suite)
.springBeans
# Code Recommenders
.recommenders/
# Annotation Processing
.apt_generated/
# Scala IDE specific (Scala & Java development for Eclipse)
.cache-main
.scala_dependencies
.worksheet
.classpath
.project

View File

@ -0,0 +1,24 @@
public class Circle implements Shape2D{
private double radius;
public Circle(double radius) {
if(radius > 0) this.radius = radius;
else this.radius = 0;
}
@Override
public double getArea() {
return Math.PI * radius * radius;
}
@Override
public double getPerimeter() {
return 2 * Math.PI * radius;
}
public String toString() {
return "Circle of radius " + radius;
}
}

View File

@ -0,0 +1,42 @@
public class Driver {
public static void main(String[] args) {
Circle circle1 = new Circle(5);
System.out.println(circle1);
System.out.println("Circle 1's Area is: " + circle1.getArea());
System.out.println("Circle 1's Perimeter is: " + circle1.getPerimeter());
System.out.println();
Circle circle2 = new Circle(8.9);
System.out.println(circle2);
System.out.println("Circle 2's Area is: " + circle2.getArea());
System.out.println("Circle 2's Perimeter is: " + circle2.getPerimeter());
System.out.println();
Circle circle3 = new Circle(-100.5);
System.out.println(circle3);
System.out.println("Circle 3's Area is: " + circle3.getArea());
System.out.println("Circle 3's Perimeter is: " + circle3.getPerimeter());
System.out.println();
Rectangle rectangle1 = new Rectangle(4.5, 8);
System.out.println(rectangle1);
System.out.println("Rectangel 1's Area is: " + rectangle1.getArea());
System.out.println("Rectangle 1's Perimeter is: " + rectangle1.getPerimeter());
System.out.println();
Rectangle rectangle2 = new Rectangle(5.4, 7.4);
System.out.println(rectangle2);
System.out.println("Rectangle 2's Area is: " + rectangle2.getArea());
System.out.println("Rectangle 2's Perimeter is: " + rectangle2.getPerimeter());
System.out.println();
Rectangle rectangle3 = new Rectangle(-4.8, 7.4);
System.out.println(rectangle3);
System.out.println("Rectangle 3's Area is: " + rectangle3.getArea());
System.out.println("Rectangle 3's Perimeter is: " + rectangle3.getPerimeter());
}
}

View File

@ -0,0 +1,31 @@
public class Rectangle implements Shape2D{
private double length;
private double width;
public Rectangle(double length, double width) {
if(length < 0 || width < 0) {
this.length = 0;
this.width = 0;
}else {
this.length = length;
this.width = width;
}
}
@Override
public double getArea() {
return length * width;
}
@Override
public double getPerimeter() {
return (2 * width) + (2 * length);
}
public String toString() {
return "Rectangle of width " + width + " and length " + length;
}
}

View File

@ -0,0 +1,8 @@
public interface Shape2D {
public double getArea();
public double getPerimeter();
}