Initial commit

This commit is contained in:
2021-03-23 22:54:32 +01:00
commit b41d133be1
106 changed files with 5423 additions and 0 deletions

View File

@@ -0,0 +1,74 @@
package debugging;
public class CoffeeCup {
private double capacity;
private double currentVolume;
public CoffeeCup() {
this.capacity = 0.0;
this.currentVolume = 0.0;
}
public CoffeeCup(double capacity, double currentVolume){
if(isValidCapacity(capacity)){
this.capacity = capacity;
}
else{
throw new IllegalArgumentException("Illegal capacity given.");
}
if(isValidVolume(currentVolume)){
this.currentVolume = currentVolume;
}
else{
throw new IllegalArgumentException("Illegal volume given.");
}
}
private boolean isValidCapacity(double capacity){
if(capacity >= 0.0){
return true;
}
return false;
}
public void increaseCupSize(double biggerCapacity){
if(isValidCapacity(biggerCapacity)){
this.capacity += biggerCapacity;
}
}
private boolean isValidVolume(double volume){
if(volume > this.capacity || volume < 0.0){
return false;
}
return true;
}
private boolean canDrink(double volume){
if(this.currentVolume >= volume){
return true;
}
return false;
}
public void drinkCoffee(double volume){
if(isValidVolume(volume) && canDrink(volume)){
this.currentVolume -= volume;
}
else{
throw new IllegalArgumentException("You can't drink that much coffee!");
}
}
public void fillCoffee(double volume){
if(isValidVolume(this.currentVolume + volume)){
this.currentVolume += volume;
}
else{
throw new IllegalArgumentException("You just poured coffee all over the table. Good job.");
}
}
}

View File

@@ -0,0 +1,59 @@
package debugging;
import java.util.Random;
public class CoffeeCupProgram {
private CoffeeCup cup;
private Random r;
public void init(){
cup = new CoffeeCup();
r = new Random(123456789L);
}
public void run(){
// part1();
part2();
}
private void part1(){
cup.increaseCupSize(40.0);
cup.fillCoffee(20.5);
cup.drinkCoffee(Math.floor(r.nextDouble()*20.5));
cup.fillCoffee(32.5);
cup.drinkCoffee(Math.ceil(r.nextDouble()*38.9));
cup.drinkCoffee(Math.ceil(r.nextDouble()*42));
cup.increaseCupSize(17);
cup.drinkCoffee(40);
cup.drinkCoffee(Math.ceil(r.nextDouble()*42));
cup.drinkCoffee(Math.floor(r.nextDouble()*20.5));
cup.fillCoffee(32.5);
cup.drinkCoffee(Math.ceil(r.nextDouble()*38.9));
cup.drinkCoffee(Math.ceil(r.nextDouble()*42));
cup.increaseCupSize(17);
}
private void part2(){
cup = new CoffeeCup(40.0, 20.5);
r = new Random(987654321L);
cup.drinkCoffee(Math.floor(r.nextDouble()*20.5));
cup.fillCoffee(Math.floor(r.nextDouble()*30));
cup.drinkCoffee(Math.ceil(r.nextDouble()*38.9));
cup.drinkCoffee(Math.ceil(r.nextDouble()*42));
cup.increaseCupSize(Math.floor(r.nextDouble()*26));
cup.fillCoffee(Math.ceil(r.nextDouble()*59));
cup.drinkCoffee(Math.ceil(r.nextDouble()*42));
cup.increaseCupSize(Math.floor(r.nextDouble()*35));
cup.fillCoffee(Math.floor(r.nextDouble()*30));
cup.increaseCupSize(Math.floor(r.nextDouble()*26));
}
public static void main(String[] args) {
CoffeeCupProgram program = new CoffeeCupProgram();
program.init();
program.run();
}
}

View File

@@ -0,0 +1,48 @@
package debugging;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class StringMergingIterator implements Iterator<String> {
private Iterator<String> first;
private Iterator<String> second;
private boolean turnSwitch;
public StringMergingIterator(Iterator<String> first, Iterator<String> second){
this.first = first;
this.second = second;
this.turnSwitch = true;
}
@Override
public boolean hasNext() {
return first.hasNext() || second.hasNext();
}
@Override
public String next() {
if(! hasNext()){ throw new NoSuchElementException(); }
String result = null;
if(! first.hasNext()){
result = second.next(); // Switch which iterator to return from
} else if(! second.hasNext()){
result = first.next();
} else {
if(turnSwitch){
result = first.next();
turnSwitch = false;
} else { // This block would execute after the previous with two ifs
result = second.next();
turnSwitch = true;
}
}
return result;
}
}

View File

@@ -0,0 +1,40 @@
package debugging;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.xtext.xbase.lib.CollectionLiterals;
public class StringMergingIteratorProgram {
public static void main(String[] args) throws Exception {
Iterator<String> one = CollectionLiterals.<String>newArrayList("a", "b").iterator();
Iterator<String> two = CollectionLiterals.<String>newArrayList("c", "d", "e").iterator();
StringMergingIterator mergeIterator = new StringMergingIterator(one, two);
List<String> values = new ArrayList<String>();
while(mergeIterator.hasNext()){
values.add(mergeIterator.next());
}
List<String> expectedOutput = CollectionLiterals.<String>newArrayList("a", "c", "b", "d", "e");
if(values.size() != expectedOutput.size()){
throw new Exception("The merged output did not contain the expected number of values. Try using the Eclipse debugger to see the difference between the lists.");
}
for(int i = 0; i < expectedOutput.size(); i++){
if(! values.get(i).equals(expectedOutput.get(i))){
throw new Exception("The iterator did not correctly merge the output. Try using the Eclipse debugger to see the difference between the lists.");
}
}
System.out.println("Success! StringMergingIterator correctly merged the output of the two lists.");
}
}

View File

@@ -0,0 +1,99 @@
package encapsulation;
public class LineEditor {
private String text = "";
private int insertionIndex = 0;
/**
* Moves the insertion index to the left (if available)
*/
public void left() {
this.insertionIndex -= (this.insertionIndex != 0) ? 1 : 0;
}
/**
* Moves the insertion index to the right (if available)
*/
public void right() {
this.insertionIndex += (this.insertionIndex != this.text.length()) ? 1 : 0;
}
/**
* Inserts a string at the insertion index and shoves the insertionIndex behind the new text.
* @param s the string to insert
*/
public void insertString(String s) {
this.text = this.text.substring(0, this.insertionIndex)
+ s
+ this.text.substring(this.insertionIndex);
this.insertionIndex += s.length();
}
/**
* Removes the character to the left of the insertionIndex (if available)
*/
public void deleteLeft() {
if (this.insertionIndex != 0) {
this.text = this.text.substring(0, this.insertionIndex - 1)
+ this.text.substring(this.insertionIndex);
this.insertionIndex--;
}
}
/**
* Removes the character to the right of the insertionIndex (if available)
*/
public void deleteRight() {
if (this.insertionIndex != this.text.length())
this.text = this.text.substring(0, this.insertionIndex)
+ this.text.substring(this.insertionIndex + 1);
}
public String getText() {
return this.text;
}
public void setText(String s) {
if (this.insertionIndex > s.length())
this.insertionIndex = s.length();
this.text = s;
this.insertionIndex = s.length();
}
public int getInsertionIndex() {
return this.insertionIndex;
}
public void setInsertionIndex(int i) throws IllegalArgumentException {
if ( i < 0 || this.text.length() < i)
throw new IllegalArgumentException("The insertion index has to be inside the scope of the text");
this.insertionIndex = i;
}
@Override
public String toString() {
return this.text.substring(0, this.insertionIndex)
+ "|"
+ this.text.substring(this.insertionIndex);
}
public static void main(String[] args) {
LineEditor lineeditor = new LineEditor();
lineeditor.setText("test");
System.out.println(lineeditor);
lineeditor.left();
System.out.println(lineeditor);
lineeditor.right();
System.out.println(lineeditor);
lineeditor.setInsertionIndex(2);
System.out.println(lineeditor);
lineeditor.deleteRight();
System.out.println(lineeditor);
lineeditor.deleteLeft();
System.out.println(lineeditor);
lineeditor.insertString("ex");
System.out.println(lineeditor);
}
}

View File

@@ -0,0 +1,230 @@
package encapsulation;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
class Person {
private String[] name = {""};
private String email = "";
private Date birthday;
private char gender = '\0';
private String ssn;
public Date getBirthday() {
return this.birthday;
}
public String getEmail() {
return this.email;
}
public char getGender() {
return this.gender;
}
public String getName() {
return String.join(" ", this.name);
}
public String getSSN() {
return this.ssn;
}
public void setName(String name) throws IllegalArgumentException {
final String nameFormat = "[A-ZÆØÅa-zæøå]{2,}";
final String fullNameFormat = String.format("%s %s", nameFormat, nameFormat);
if (!name.matches(fullNameFormat))
throw new IllegalArgumentException("Couldn't parse name");
this.name = name.split(" ");
}
private boolean checkEmail(String email) {
final Set<String> cTLDs = Set.of("ad", "ae", "af", "ag", "ai", "al", "am", "ao", "aq", "ar", "as", "at", "au", "aw",
"ax", "az", "ba", "bb", "bd", "be", "bf", "bg", "bh", "bi", "bj", "bl", "bm", "bn", "bo", "bq", "br", "bs",
"bt", "bv", "bw", "by", "bz", "ca", "cc", "cd", "cf", "cg", "ch", "ci", "ck", "cl", "cm", "cn", "co", "cr",
"cu", "cv", "cw", "cx", "cy", "cz", "de", "dj", "dk", "dm", "do", "dz", "ec", "ee", "eg", "eh", "er", "es",
"et", "fi", "fj", "fk", "fm", "fo", "fr", "ga", "gb", "gd", "ge", "gf", "gg", "gh", "gi", "gl", "gm", "gn",
"gp", "gq", "gr", "gs", "gt", "gu", "gw", "gy", "hk", "hm", "hn", "hr", "ht", "hu", "id", "ie", "il", "im",
"in", "io", "iq", "ir", "is", "it", "je", "jm", "jo", "jp", "ke", "kg", "kh", "ki", "km", "kn", "kp", "kr",
"kw", "ky", "kz", "la", "lb", "lc", "li", "lk", "lr", "ls", "lt", "lu", "lv", "ly", "ma", "mc", "md", "me",
"mf", "mg", "mh", "mk", "ml", "mm", "mn", "mo", "mp", "mq", "mr", "ms", "mt", "mu", "mv", "mw", "mx", "my",
"mz", "na", "nc", "ne", "nf", "ng", "ni", "nl", "no", "np", "nr", "nu", "nz", "om", "pa", "pe", "pf", "pg",
"ph", "pk", "pl", "pm", "pn", "pr", "ps", "pt", "pw", "py", "qa", "re", "ro", "rs", "ru", "rw", "sa", "sb",
"sc", "sd", "se", "sg", "sh", "si", "sj", "sk", "sl", "sm", "sn", "so", "sr", "ss", "st", "sv", "sx", "sy",
"sz", "tc", "td", "tf", "tg", "th", "tj", "tk", "tl", "tm", "tn", "to", "tr", "tt", "tv", "tw", "tz", "ua",
"ug", "um", "us", "uy", "uz", "va", "vc", "ve", "vg", "vi", "vn", "vu", "wf", "ws", "ye", "yt", "za", "zm",
"zw");
String[] emailParts = email.split("[.@]");
if (emailParts.length != 4) return false;
return Stream.of(
emailParts[0].equalsIgnoreCase(this.name[0]),
emailParts[1].equalsIgnoreCase(this.name[1]),
emailParts[2].matches("[A-Za-z0-9]+"), // "\w" includes '_', so it's no good here.
cTLDs.contains(emailParts[3])
).allMatch(b -> b);
}
public void setEmail(String email) throws IllegalArgumentException {
if (!checkEmail(email))
throw new IllegalArgumentException("Couldn't parse email. Is the name correct?");
this.email = email;
}
public void setBirthday(Date birthday) throws IllegalArgumentException {
Date now = new Date(System.currentTimeMillis());
if (!birthday.before(now))
throw new IllegalArgumentException("This date is invalid. Please set a date in the past.");
this.birthday = birthday;
}
public void setGender(char gender) throws IllegalArgumentException {
final Set<Character> legalGenders = Set.of('M', 'F', '\0');
if (!legalGenders.contains(gender))
throw new IllegalArgumentException("Couldn't parse gender.");
this.gender = gender;
}
/**
* Emphasize a range of characters within a String
* @param s The string to modify
* @param start The start index of the range
* @param end The end index of the range
* @return The modified string with an emphazised range
*/
private static String emphasizeStringRange(String s, int start, int end)
throws IndexOutOfBoundsException {
return s.substring(0, start)
+ " <"
+ s.substring(start, end)
+ "> "
+ s.substring(end);
}
/**
* Make sure that the birthdate of the SSN is equal to the
* birthday of the person
* @param ssn The SSN to validate
*/
private void checkSSNBirthday(String ssn) throws IllegalArgumentException {
// Calendar birthdate = Calendar.getInstance();
try {
Date birthday =
DateFormat
.getDateInstance(DateFormat.SHORT)
.parse(
ssn.substring(0, 2) + "/" +
ssn.substring(2, 4) + "/" +
ssn.substring(4, 6)
);
if (!birthday.equals(this.birthday))
throw new IllegalArgumentException(
"The SSN birthday does not match this persons birthday"
);
} catch (ParseException e) {
throw new IllegalArgumentException(
"Could not parse SSN date: " + emphasizeStringRange(ssn, 0, 6)
);
}
}
/**
* Make sure that the SSN is valid based on the persons gender
* @param ssn The ssn to validate
*/
private void checkSSNMaleFemaleDigit(String ssn) throws IllegalArgumentException {
int maleOrFemaleDigit = Integer.parseInt(ssn.substring(8, 9));
boolean isMale = maleOrFemaleDigit % 2 == 1;
boolean isGenderCorrect =
(this.gender == 'M' && isMale) || (this.gender == 'F' && !isMale);
if (!isGenderCorrect)
throw new IllegalArgumentException(
"The digit "
+ emphasizeStringRange(ssn, 8, 9)
+ " has to be different because the person is a "
+ (isMale ? "male" : "female")
);
}
/**
* Check that the control ciphers are valid.
* @param ssn The SSN to validate
*/
private void checkSSNControlCiphers(String ssn) throws IllegalArgumentException {
final List<Integer> f = List.of(3, 7, 6, 1, 8, 9, 4, 5, 2);
final List<Integer> g = List.of(5, 4, 3, 2, 7, 6, 5, 4, 3, 2);
final BiFunction<List<Integer>, List<Integer>, Integer> processDigits =
(ds, cs) ->
IntStream
.range(0, ds.size())
.map(i -> ds.get(i) * cs.get(i))
.sum();
List<Integer> digits =
ssn
.substring(0, 9)
.chars()
.map(c -> c - '0') // remove offset from 0x00 to '0'
.boxed() // IntStream -> Stream<Integer>
.collect(Collectors.toList());
Integer k1 = 11 - processDigits.apply(digits, f) % 11;
digits.add(k1);
Integer k2 = 11 - processDigits.apply(digits, g) % 11;
boolean isControlCiphersCorrect =
(k1.toString() + k2.toString())
.equals(ssn.substring(9));
if (!isControlCiphersCorrect)
throw new IllegalArgumentException(
String.format(
"""
Control ciphers do not match the given input: %s
Expected: %s""",
emphasizeStringRange(ssn, 9, 11),
(k1 + " " + k2)
)
);
}
/**
* Validate an SSN based on the persons info.
* {@link #setBirthday(Date) setBirthday()} and {@link #setGender(char) setGender()}
* must have been run in order for this function to work.
* @param ssn The SSN to validate
*/
private void checkSSN(String ssn) throws IllegalArgumentException {
if (!ssn.matches("\\d{11}"))
throw new IllegalArgumentException("The amount of digits does not match the expected amount");
checkSSNBirthday(ssn);
checkSSNMaleFemaleDigit(ssn);
checkSSNControlCiphers(ssn);
}
public void setSSN(String ssn) throws IllegalArgumentException {
checkSSN(ssn);
this.ssn = ssn;
}
}

View File

@@ -0,0 +1,58 @@
package encapsulation;
import java.util.EmptyStackException;
import java.util.Stack;
public class RPNCalc {
// Using stack instead of Deque in order to get access to elementAt(i)
private Stack<Double> stack = new Stack<Double>();
public void push(double num) {
this.stack.push(num);
}
public double pop() {
Double result = this.stack.pop();
return result.isNaN() ? Double.NaN : result;
}
public double peek(int i) {
return this.getSize() >= (i + 1) && i >= 0
? this.stack.elementAt(this.getSize() - 1 - i)
: Double.NaN;
}
public int getSize() {
return this.stack.size();
}
public void performOperation(char op) throws IllegalArgumentException {
double a, b;
try {
a = this.stack.pop();
b = this.stack.pop();
} catch (EmptyStackException e) {
throw new IllegalArgumentException("Not enough numbers in the calculator");
}
switch (op) {
case '+':
this.stack.push(b + a);
break;
case '-':
this.stack.push(b - a);
break;
case '*':
this.stack.push(b * a);
break;
case '/':
this.stack.push(b / a);
break;
case '^':
this.stack.push(Math.pow(a, b));
break;
default:
throw new IllegalArgumentException("No such operator implemented: " + op);
}
}
}

View File

@@ -0,0 +1,83 @@
package encapsulation;
class Vehicle {
private final char type;
private final char fuel;
private String registrationNumber;
Vehicle(char type, char fuel, String registrationNumber) {
this.type = type;
this.fuel = fuel;
this.setRegistrationNumber(registrationNumber);
}
public char getVehicleType() {
return this.type;
}
public char getFuelType() {
return this.fuel;
}
public String getRegistrationNumber() {
return this.registrationNumber;
}
public void setRegistrationNumber(String registrationNumber) {
if (!checkRegistrationNumber(registrationNumber))
throw new IllegalArgumentException("Could not parse registration number.");
if (!checkFuelType(this.fuel, registrationNumber))
throw new IllegalArgumentException("This registration number is not valid for a vehicle with this type of fuel. The fuel type has to be given in upper case.");
if (!checkVehicleType(this.type, registrationNumber))
throw new IllegalArgumentException("This registration number is not valid for a vehicle of this type.");
this.registrationNumber = registrationNumber;
}
/**
* Test whether or not the registration number is syntactically valid.
*
* @return Whether or not the test was passed
*/
private static boolean checkRegistrationNumber(String registrationNumber) {
return registrationNumber.matches("[A-Z]{2}\\d{4,5}");
}
/**
* Test whether or not the registration number is valid based on the fuel type.
*
* @return Whether or not the test was passed
*/
private static boolean checkFuelType(char fuel, String registrationNumber) {
switch(fuel) {
case 'H':
return registrationNumber.matches("HY\\d+");
case 'E':
return registrationNumber.matches("(?:EL|EK)\\d+");
case 'D':
case 'G':
return registrationNumber.matches("(?!EL|EK|HY)[A-Z]{2}\\d+");
default:
return false;
}
}
/**
* Test whether or not the registration number is valid based on the vehicle type.
*
* @return Whether or not the test was passed
*/
private static boolean checkVehicleType(char type, String registrationNumber) {
switch(type) {
case 'C':
return registrationNumber.matches("[A-Z]{2}\\d{5}");
case 'M':
return registrationNumber.matches("(?!HY)[A-Z]{2}\\d{4}");
default:
return false;
}
}
}

View File

@@ -0,0 +1,57 @@
package interfaces;
import static org.junit.Assert.assertThrows;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.function.BinaryOperator;
public class BinaryComputingIterator implements Iterator<Double> {
private Iterator<Double> iterator1;
private Iterator<Double> iterator2;
private Optional<Double> default1 = Optional.empty();
private Optional<Double> default2 = Optional.empty();
private BinaryOperator<Double> operator;
public BinaryComputingIterator(Iterator<Double> iterator1,
Iterator<Double> iterator2,
BinaryOperator<Double> operator)
{
this.iterator1 = iterator1;
this.iterator2 = iterator2;
this.operator = operator;
}
public BinaryComputingIterator(Iterator<Double> iterator1,
Iterator<Double> iterator2,
Double default1,
Double default2,
BinaryOperator<Double> operator)
{
this.iterator1 = iterator1;
this.iterator2 = iterator2;
this.operator = operator;
this.default1 = Optional.ofNullable(default1);
this.default2 = Optional.ofNullable(default2);
}
@Override
public Double next() {
return this.operator.apply(
this.iterator1.hasNext() ? this.iterator1.next() : this.default1.orElseThrow(),
this.iterator2.hasNext() ? this.iterator2.next() : this.default2.orElseThrow()
);
}
@Override
public boolean hasNext() {
return this.default1.isPresent() || this.default2.isPresent()
? this.iterator1.hasNext() || this.iterator2.hasNext()
: this.iterator1.hasNext() && this.iterator2.hasNext();
}
}

View File

@@ -0,0 +1,64 @@
package interfaces;
import java.util.EmptyStackException;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
import java.util.function.BinaryOperator;
public class RPNCalc {
// Using stack instead of Deque in order to get access to elementAt(i)
private Stack<Double> stack = new Stack<>();
private Map<Character, BinaryOperator<Double>> operators = new HashMap<>();
public void push(double num) {
this.stack.push(num);
}
public double pop() {
try {
return this.stack.pop();
} catch (EmptyStackException e) {
return Double.NaN;
}
}
public double peek(int i) {
return this.getSize() >= (i + 1) && i >= 0
? this.stack.elementAt(this.getSize() - 1 - i)
: Double.NaN;
}
public int getSize() {
return this.stack.size();
}
public boolean addOperator(char op, BinaryOperator<Double> opFunc) {
if (this.operators.get(op) != null)
return false;
this.operators.put(op, opFunc);
return true;
}
public void removeOperator(char op) {
this.operators.remove(op);
}
public void performOperation(char op)
throws UnsupportedOperationException, IllegalArgumentException {
if (this.operators.get(op) == null)
throw new UnsupportedOperationException("Operator " + op + " does not exist");
double a, b;
try {
a = this.stack.pop();
b = this.stack.pop();
} catch (EmptyStackException e) {
throw new IllegalArgumentException("Not enough numbers in the calculator");
}
this.stack.push(this.operators.get(op).apply(b, a));
}
}

View File

@@ -0,0 +1,78 @@
package meta;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import encapsulation.RPNCalc;
import objectstructures.Person;
public class ClassDiagram {
private Class<?> cls;
ClassDiagram(Class<?> cls) {
this.cls = cls;
}
private char detectModifiers(Member m) {
String firstModifier =
Modifier
.toString(m.getModifiers())
.split("\\s")[0];
return firstModifier == "public" ? '+' : '-';
}
private String formatFields() {
return
Stream.of(this.cls.getDeclaredFields())
.map(f -> detectModifiers(f) + f.getName() + ": " + f.getType().getSimpleName())
.collect(Collectors.joining("\n "));
}
private String formatParameters(Method m) {
return
Stream.of(m.getParameters())
.map(p -> p.getType().getSimpleName() + " " + p.getName())
.collect(Collectors.joining(", "));
}
private String formatMethods() {
return
Stream.of(this.cls.getDeclaredMethods())
.map(m ->
String.format(
"%c%s(%s): %s"
, detectModifiers(m)
, m.getName()
, formatParameters(m)
, m.getReturnType().getSimpleName()
))
.collect(Collectors.joining("\n "));
}
@Override
public String toString() {
return String.format(
"""
class %s {
%s
%s
}
"""
, this.cls.getName()
, this.formatFields()
, this.formatMethods()
);
}
public static void main(String[] args) {
ClassDiagram cd = new ClassDiagram(Person.class);
System.out.println(cd);
}
}

View File

@@ -0,0 +1,13 @@
/**
* @author hal
*
*/
open module ovinger {
requires javafx.base;
requires javafx.controls;
requires javafx.fxml;
requires javafx.graphics;
requires junit;
requires org.eclipse.xtext.xbase.lib;
// requires no.hal.jex.jextest.lib;
}

View File

@@ -0,0 +1,81 @@
package objectstructures;
public class CoffeeCup {
private double capacity;
private double currentVolume;
public CoffeeCup() {
this.capacity = 0.0;
this.currentVolume = 0.0;
}
public CoffeeCup(double capacity, double currentVolume){
if(isValidCapacity(capacity)){
this.capacity = capacity;
}
else{
throw new IllegalArgumentException("Illegal capacity given.");
}
if(isValidVolume(currentVolume)){
this.currentVolume = currentVolume;
}
else{
throw new IllegalArgumentException("Illegal volume given.");
}
}
public double getCapacity() {
return capacity;
}
public double getCurrentVolume() {
return currentVolume;
}
private boolean isValidCapacity(double capacity){
if(capacity >= 0.0){
return true;
}
return false;
}
public void increaseCupSize(double biggerCapacity){
if(isValidCapacity(biggerCapacity)){
this.capacity += biggerCapacity;
}
}
private boolean isValidVolume(double volume){
if(volume > this.capacity || volume < 0.0){
return false;
}
return true;
}
private boolean canDrink(double volume){
if(this.currentVolume >= volume){
return true;
}
return false;
}
public void drinkCoffee(double volume){
if(isValidVolume(volume) && canDrink(volume)){
this.currentVolume -= volume;
}
else{
throw new IllegalArgumentException("You can't drink that much coffee!");
}
}
public void fillCoffee(double volume){
if(isValidVolume(this.currentVolume + volume)){
this.currentVolume += volume;
}
else{
throw new IllegalArgumentException("You just poured coffee all over the table. Good job.");
}
}
}

View File

@@ -0,0 +1,102 @@
package objectstructures;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
public class Person {
private String name;
private char gender;
private List<Person> children = new ArrayList<>();
private Optional<Person> mother = Optional.empty();
private Optional<Person> father = Optional.empty();
public Person(String name, char gender) {
this.name = name;
this.gender = gender;
}
public String getName() {
return name;
}
public char getGender() {
return gender;
}
public Collection<Person> getChildren() {
return children;
}
public int getChildCount() {
return children.size();
}
public Person getChild(int n) {
if (0 > n || n >= this.children.size())
throw new IllegalArgumentException("Child " + n + " doesn't exist");
return this.children.get(n);
}
public Person getMother() {
return mother.orElse(null);
}
public Person getFather() {
return father.orElse(null);
}
public void addChild(Person child) {
this.children.add(child);
if (this.gender == 'M' && child.getFather() != this)
child.setFather(this);
else if (this.gender == 'F' && child.getMother() != this)
child.setMother(this);
}
public void removeChild(Person child) {
this.children.remove(child);
if (this.gender == 'M' && child.getFather() == this)
child.setFather(null);
else if (this.gender == 'F' && child.getMother() == this)
child.setMother(null);
}
private void setParent(Person newParent,
Optional<Person> currentParent,
char gender)
{
if (newParent != null && newParent.getGender() != gender)
throw new IllegalArgumentException("Gender mismatch");
if (newParent == this)
throw new IllegalArgumentException("A person can not be its own parent");
var previousParent = currentParent;
currentParent = Optional.ofNullable(newParent);
if (newParent.getGender() == 'M')
this.father = Optional.ofNullable(newParent);
else
this.mother = Optional.ofNullable(newParent);
currentParent.ifPresent(p -> {
if (!p.getChildren().contains(this)) p.addChild(this);
});
previousParent.ifPresent(p -> p.removeChild(this));
}
public void setMother(Person mother) {
setParent(mother, this.mother, 'F');
}
public void setFather(Person father) {
setParent(father, this.father, 'M');
}
}

View File

@@ -0,0 +1,23 @@
package setupcheck;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
public class GuiWorks extends Application {
public void start(Stage stage) {
Label hello = new Label("Om du ser denne teksten, så kan du kompilere og kjøre Java!");
AnchorPane pane = new AnchorPane();
pane.getChildren().add(hello);
stage.setScene(new Scene(pane));
stage.show();
}
public static void main(String... args) {
Application.launch(args);
}
}

View File

@@ -0,0 +1,22 @@
package setupcheck;
public class SimpleClass {
private int myVal;
public SimpleClass(int myVal) {
this.myVal = myVal;
}
public int getMyVal() {
return myVal;
}
public static void main(String... args) {
Object o = "**The program runs**"; // Don't write code like this at home
// Check that preview features are enabled
if (o instanceof String s) {
System.out.println(s.substring(2, s.length()-2));
}
}
}

View File

@@ -0,0 +1,90 @@
package stateandbehavior;
public class LineEditor {
private String text = "";
private int insertionIndex = 0;
/** flytter tekstinnsettingsposisjonen ett tegn til venstre (tilsvarende bruk av venstre piltast) */
public void left() {
this.insertionIndex -= (this.insertionIndex != 0) ? 1 : 0;
}
/** flytter tekstinnsettingsposisjonen ett tegn til høyre (tilsvarende bruk av høyre piltast) */
public void right() {
this.insertionIndex += (this.insertionIndex != this.text.length()) ? 1 : 0;
}
/** skyter teksten angitt av argumentet s inn i teksten på tekstinnsettingsposisjonen og forskyver tekstinnsettingsposisjonen mot høyre tilsvarende */
public void insertString(String s) {
this.text = this.text.substring(0, this.insertionIndex)
+ s
+ this.text.substring(this.insertionIndex);
this.insertionIndex += s.length();
}
/** fjerner tegnet til venstre for tekstinnsettingsposisjonen */
public void deleteLeft() {
if (this.insertionIndex != 0) {
this.text = this.text.substring(0, this.insertionIndex - 1)
+ this.text.substring(this.insertionIndex);
this.insertionIndex--;
}
}
/** fjerner tegnet til høyre for tekstinnsettingsposisjonen */
public void deleteRight() {
if (this.insertionIndex != this.text.length())
this.text = this.text.substring(0, this.insertionIndex)
+ this.text.substring(this.insertionIndex + 1);
}
/** returnerer teksten */
public String getText() {
return this.text;
}
/** oppdaterer teksten til å være den nye teksten */
public void setText(String s) {
this.text = s;
}
/** returnerer hvor i teksten redigeringer nå skjer */
public int getInsertionIndex() {
return this.insertionIndex;
}
/** oppdaterer hvor i teksten redigeringer skal skje */
public void setInsertionIndex(int i) {
this.insertionIndex = i;
}
@Override
public String toString() {
return this.text.substring(0, this.insertionIndex)
+ "|"
+ this.text.substring(this.insertionIndex);
}
public static void main(String[] args) {
LineEditor lineeditor = new LineEditor();
lineeditor.setText("test");
System.out.println(lineeditor);
lineeditor.right();
System.out.println(lineeditor);
lineeditor.left();
System.out.println(lineeditor);
lineeditor.setInsertionIndex(2);
System.out.println(lineeditor);
lineeditor.deleteRight();
System.out.println(lineeditor);
lineeditor.deleteLeft();
System.out.println(lineeditor);
lineeditor.insertString("ex");
System.out.println(lineeditor);
}
}

View File

@@ -0,0 +1,161 @@
package stateandbehavior;
import java.util.Arrays;
public class Rectangle {
private int[] minPoint;
private int[] maxPoint;
public Rectangle() {
this.minPoint = (new int[] {});
this.maxPoint = (new int[] {});
}
/**
* returnerer henholdsvis x- og y-koordinatene til punktet med
* lavest (x,y)-verdier som er inneholdt i dette rektanglet. Dersom dette rektanglet er tomt, så skal 0 returneres.
*/
public int getMinX() {
return this.isEmpty() ? 0 : this.minPoint[0];
}
/**
* Se {@link #getMinX() getMinX()}
*/
public int getMinY() {
return this.isEmpty() ? 0 : this.minPoint[1];
}
/**
* returnerer henholdsvis x- og y-koordinatene til punktet med høyest (x,y)-verdier som er inneholdt i dette rektanglet. Dersom dette rektanglet er tomt, så skal 0 returneres.
*/
public int getMaxX() {
return this.isEmpty() ? 0 : this.maxPoint[0];
}
/**
* Se {@link #getMaxX() getMaxX()}
*/
public int getMaxY() {
return this.isEmpty() ? 0 : this.maxPoint[1];
}
/** returnerer henholdsvis bredden og høyden til rektanglet. Begge skal returnere 0, dersom dette rektanglet er tomt. */
public int getWidth() {
if (this.isEmpty()) return 0;
return this.maxPoint[0] - this.minPoint[0] + 1;
}
public int getHeight() {
if (this.isEmpty()) return 0;
return this.maxPoint[1] - this.minPoint[1] + 1;
}
/** returnerer true om rektanglet er tomt, dvs. om bredden og/eller høyden er 0. */
public boolean isEmpty(){
return this.minPoint.length == 0;
}
/** returnerer true om punktet (x,y) er inneholdt i dette rektanglet, og false ellers. */
public boolean contains(int x, int y) {
if (this.isEmpty()) return false;
return Arrays.asList(
(this.maxPoint[0] >= x),
(this.maxPoint[1] >= y),
(this.minPoint[0] <= x),
(this.minPoint[1] <= y))
.stream()
.allMatch(b -> b);
}
/** returnerer true om hele rect, dvs. alle punktene i rect, er inneholdt i dette rektanglet, og false ellers. Dersom rect er tomt, så skal false returneres. */
public boolean contains(Rectangle rect) {
if (rect.isEmpty()) return false;
return this.contains(rect.getMaxX(), rect.getMaxY())
&& this.contains(rect.getMinX(), rect.getMinY());
}
/** utvider (om nødvendig) dette rektanglet slik at det (akkurat) inneholder punktet (x,y). Etter kallet skal altså contains(x, y) returnere true. Returnerer true om dette rektanglet faktisk ble endret, ellers false. */
public boolean add(int x, int y) {
if (this.isEmpty()) {
this.maxPoint = (new int[] {x, y});
this.minPoint = (new int[] {x, y});
return true;
}
boolean wasChanged = false;
if (x > this.maxPoint[0]) {
this.maxPoint[0] = x;
wasChanged = true;
}
if (y > this.maxPoint[1]) {
this.maxPoint[1] = y;
wasChanged = true;
}
if (x < this.minPoint[0]) {
this.minPoint[0] = x;
wasChanged = true;
}
if (y < this.minPoint[1]) {
this.minPoint[1] = y;
wasChanged = true;
}
return wasChanged;
}
/** utvider (om nødvendig) dette rektanglet slik at det (akkurat) inneholder hele rect-argumentet. Returnerer true om dette rektanglet faktisk ble endret, ellers false. Dersom rect er tomt, så skal dette rektanglet ikke endres. */
public boolean add(Rectangle rect) {
boolean addedp1 = this.add(rect.getMaxX(), rect.getMaxY());
boolean addedp2 = this.add(rect.getMinX(), rect.getMinY());
return (addedp1 || addedp2);
}
/** returnerer et nytt Rectangle-objekt som tilsvarer kombisjonen av dette rektanglet og rect-argumentet. Alle punktene som finnes i ett av rektanglene skal altså være inneholdt i rektanglet som returneres. */
public Rectangle union(Rectangle rect) {
Rectangle result = new Rectangle();
result.add(this);
result.add(rect);
return result;
}
/** returnerer et nytt Rectangle-objekt som tilsvarer overlappet mellom dette rektanglet og rect-argumentet. Alle punktene som finnes i begge rektanglene skal altså være inneholdt i rektanglet som returneres. */
public Rectangle intersection(Rectangle rect) {
if (this.intersects(rect)) {
int maxX = Math.max(this.minPoint[0], rect.getMinX());
int maxY = Math.max(this.minPoint[1], rect.getMinY());
int minX = Math.min(this.maxPoint[0], rect.getMaxX());
int minY = Math.min(this.maxPoint[1], rect.getMaxY());
Rectangle result = new Rectangle();
result.add(minX, minY);
result.add(maxX, maxY);
return result;
} else {
return new Rectangle();
}
}
/** returnerer true om dette rektanglet og rect-argumentet overlapper, dvs. om det finnes ett eller flere punkter som er inneholdt i begge disse rektanglene. */
public boolean intersects(Rectangle rect) {
if (this.isEmpty() || rect.isEmpty()) return false;
return !((this.minPoint[0] > rect.getMaxX() || rect.getMinX() > this.maxPoint[0])
&& (this.minPoint[1] > rect.getMaxY() || rect.getMinY() > this.maxPoint[1]));
}
@Override
public String toString() {
if (this.isEmpty()) return "Empty";
return String.format("(%d, %d), (%d, %d), [%d x %d]",
minPoint[0],
minPoint[1],
maxPoint[0],
maxPoint[1],
getWidth(),
getHeight()
);
}
}

View File

@@ -0,0 +1,111 @@
package stateandbehavior;
public class StopWatch {
private int totalTicks = 0;
private int totalTime = 0;
private int lapTimeOffset = 0; // amount of ticks at end of last lap
private int lastLapTimeOffset = -1; // amount of ticks at start of last lap
private boolean hasBeenStarted = false;
private boolean hasBeenStopped = false;
/** returnerer true om klokken har blitt startet eller false om den ikke har blitt startet */
public boolean isStarted() {
return this.hasBeenStarted;
}
/** returnerer true om klokken har blitt stoppet eller false om den ikke har blitt stoppet. Merk at her snakker vi om at klokken har blitt stoppet, ikke om klokken går eller ikke. */
public boolean isStopped() {
return this.hasBeenStopped;
}
/** returnerer det totale antall tikk (millisekunder) som har gått i levetiden til klokken uavhengig om klokken har vært startet eller stoppet. */
public int getTicks() {
return this.totalTicks;
}
/** returnerer antall tikk som har gått under tidtakningen. Hvis tidtakningen ikke har startet returner -1. Merk at hvis klokken er startet, men ikke stoppet, skal metoden returnere antall tikk som har gått siden klokken ble startet til nå. Hvis klokken er stoppet skal metoden returnere antall tikk som har gått fra klokken ble startet til klokken ble stoppet. */
public int getTime() {
return this.hasBeenStarted ? totalTime : -1;
}
/** returnerer antall tikk som har gått under nåværende rundetid til nå. Hvis tidtakningen ikke har startet returner -1. */
public int getLapTime() {
return this.hasBeenStarted ? totalTime - lapTimeOffset : -1;
}
/** returnerer lengden på forrige avsluttede rundetid. Hvis det ikke er noen tidligere rundetider returner -1. */
public int getLastLapTime() {
return this.lastLapTimeOffset != -1
? lapTimeOffset - lastLapTimeOffset
: -1;
}
/** forteller klokken at ticks antall tikk har gått. */
public void tick(int ticks) {
// this.totalTicks += ticks;
if (this.hasBeenStarted ^ this.hasBeenStopped)
this.totalTime += ticks;
}
/** starter klokken. */
public void start() {
this.hasBeenStarted = true;
}
/** avslutter nåværende rundetid og starter en ny. */
public void lap() {
this.lastLapTimeOffset = this.lapTimeOffset;
this.lapTimeOffset = this.totalTime;
}
/** stopper klokken. */
public void stop() {
if (this.hasBeenStarted) {
this.lap();
this.hasBeenStopped = true;
}
}
public String toString() {
return String.format(
"""
{
id: %d
ticks: %d
time: %d
currentLap: %d
lastLap: %d
hasStarted: %b
hasStopped: %b
}
"""
, this.hashCode()
, this.totalTicks
, this.getTime()
, this.getLapTime()
, this.getLastLapTime()
, this.hasBeenStarted
, this.hasBeenStopped
);
}
public static void main(String[] args) {
StopWatch sw = new StopWatch();
System.out.println(sw);
sw.tick(1);
System.out.println(sw);
sw.start();
System.out.println(sw);
sw.tick(3);
System.out.println(sw);
sw.lap();
System.out.println(sw);
sw.tick(2);
System.out.println(sw);
sw.stop();
System.out.println(sw);
sw.tick(2);
System.out.println(sw);
}
}

View File

@@ -0,0 +1,165 @@
package encapsulation;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class LineEditorTest {
private LineEditor lineEditor;
@BeforeEach
public void setup() {
lineEditor = new LineEditor();
}
@Test
public void testConstructor() {
Assertions.assertEquals("", lineEditor.getText());
Assertions.assertEquals(0, lineEditor.getInsertionIndex());
}
@Test
public void testGetSetText() {
lineEditor.setText("ABC");
Assertions.assertEquals("ABC", lineEditor.getText());
Assertions.assertEquals(3, lineEditor.getInsertionIndex());
lineEditor.setText("");
Assertions.assertEquals("", lineEditor.getText());
Assertions.assertEquals(0, lineEditor.getInsertionIndex());
}
@Test
public void testGetSetInsertionIndex() {
lineEditor.setText("ABC");
Assertions.assertEquals("ABC", lineEditor.getText());
Assertions.assertEquals(3, lineEditor.getInsertionIndex());
lineEditor.setInsertionIndex(0);
Assertions.assertEquals("ABC", lineEditor.getText());
Assertions.assertEquals(0, lineEditor.getInsertionIndex());
lineEditor.setInsertionIndex(3);
Assertions.assertEquals("ABC", lineEditor.getText());
Assertions.assertEquals(3, lineEditor.getInsertionIndex());
}
@Test
public void testLeft() {
lineEditor.setText("Ja");
lineEditor.setInsertionIndex(2);
lineEditor.left();
Assertions.assertEquals("Ja", lineEditor.getText());
Assertions.assertEquals(1, lineEditor.getInsertionIndex());
lineEditor.left();
Assertions.assertEquals(0, lineEditor.getInsertionIndex());
lineEditor.left();
Assertions.assertEquals(0, lineEditor.getInsertionIndex());
}
@Test
public void testRight() {
lineEditor.setText("Ja");
lineEditor.setInsertionIndex(0);
lineEditor.right();
Assertions.assertEquals("Ja", lineEditor.getText());
Assertions.assertEquals(1, lineEditor.getInsertionIndex());
lineEditor.right();
Assertions.assertEquals(2, lineEditor.getInsertionIndex());
lineEditor.right();
Assertions.assertEquals(2, lineEditor.getInsertionIndex());
}
@Test
public void testDeleteLeft() {
lineEditor.setText("Ja");
lineEditor.setInsertionIndex(0);
lineEditor.deleteLeft();
Assertions.assertEquals("Ja", lineEditor.getText());
Assertions.assertEquals(0, lineEditor.getInsertionIndex());
lineEditor.setInsertionIndex(1);
lineEditor.deleteLeft();
Assertions.assertEquals("a", lineEditor.getText());
Assertions.assertEquals(0, lineEditor.getInsertionIndex());
lineEditor.deleteLeft();
Assertions.assertEquals("a", lineEditor.getText());
Assertions.assertEquals(0, lineEditor.getInsertionIndex());
lineEditor.setText("Ja");
lineEditor.setInsertionIndex(2);
lineEditor.deleteLeft();
Assertions.assertEquals("J", lineEditor.getText());
Assertions.assertEquals(1, lineEditor.getInsertionIndex());
lineEditor.deleteLeft();
Assertions.assertEquals("", lineEditor.getText());
Assertions.assertEquals(0, lineEditor.getInsertionIndex());
lineEditor.deleteLeft();
Assertions.assertEquals("", lineEditor.getText());
Assertions.assertEquals(0, lineEditor.getInsertionIndex());
}
@Test
public void testDeleteRight() {
lineEditor.setText("Ja");
lineEditor.setInsertionIndex(2);
lineEditor.deleteRight();
Assertions.assertEquals("Ja", lineEditor.getText());
Assertions.assertEquals(2, lineEditor.getInsertionIndex());
lineEditor.setInsertionIndex(1);
lineEditor.deleteRight();
Assertions.assertEquals("J", lineEditor.getText());
Assertions.assertEquals(1, lineEditor.getInsertionIndex());
lineEditor.deleteRight();
Assertions.assertEquals("J", lineEditor.getText());
Assertions.assertEquals(1, lineEditor.getInsertionIndex());
lineEditor.setText("Ja");
lineEditor.setInsertionIndex(0);
lineEditor.deleteRight();
Assertions.assertEquals("a", lineEditor.getText());
Assertions.assertEquals(0, lineEditor.getInsertionIndex());
lineEditor.deleteRight();
Assertions.assertEquals("", lineEditor.getText());
Assertions.assertEquals(0, lineEditor.getInsertionIndex());
lineEditor.deleteRight();
Assertions.assertEquals("", lineEditor.getText());
Assertions.assertEquals(0, lineEditor.getInsertionIndex());
}
@Test
public void testInsertString() {
lineEditor.insertString("");
Assertions.assertEquals("", lineEditor.getText());
Assertions.assertEquals(0, lineEditor.getInsertionIndex());
lineEditor.insertString("Java");
Assertions.assertEquals("Java", lineEditor.getText());
Assertions.assertEquals(4, lineEditor.getInsertionIndex());
lineEditor.insertString(" er gøy!");
Assertions.assertEquals("Java er gøy!", lineEditor.getText());
Assertions.assertEquals(12, lineEditor.getInsertionIndex());
lineEditor.setText("Javagøy!");
lineEditor.setInsertionIndex(4);
lineEditor.insertString(" er ");
Assertions.assertEquals("Java er gøy!", lineEditor.getText());
Assertions.assertEquals(8, lineEditor.getInsertionIndex());
lineEditor.setText("er gøy!");
lineEditor.setInsertionIndex(0);
lineEditor.insertString("Java ");
Assertions.assertEquals("Java er gøy!", lineEditor.getText());
Assertions.assertEquals(5, lineEditor.getInsertionIndex());
}
}

View File

@@ -0,0 +1,176 @@
package encapsulation;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class LineEditorTest2 {
private LineEditor lineEditor;
@BeforeEach
public void setup() {
lineEditor = new LineEditor();
}
@Test
public void testConstructor() {
Assertions.assertEquals("", lineEditor.getText());
Assertions.assertEquals(0, lineEditor.getInsertionIndex());
}
@Test
public void testGetSetText() {
lineEditor.setText("ABC");
Assertions.assertEquals("ABC", lineEditor.getText());
Assertions.assertEquals(3, lineEditor.getInsertionIndex());
lineEditor.setText("");
Assertions.assertEquals("", lineEditor.getText());
Assertions.assertEquals(0, lineEditor.getInsertionIndex());
}
@Test
public void testGetSetInsertionIndex() {
lineEditor.setText("ABC");
Assertions.assertEquals("ABC", lineEditor.getText());
Assertions.assertEquals(3, lineEditor.getInsertionIndex());
lineEditor.setInsertionIndex(0);
Assertions.assertEquals("ABC", lineEditor.getText());
Assertions.assertEquals(0, lineEditor.getInsertionIndex());
lineEditor.setInsertionIndex(3);
Assertions.assertEquals("ABC", lineEditor.getText());
Assertions.assertEquals(3, lineEditor.getInsertionIndex());
Assertions.assertThrows(IllegalArgumentException.class, () -> {
lineEditor.setInsertionIndex(-1);
});
Assertions.assertThrows(IllegalArgumentException.class, () -> {
lineEditor.setInsertionIndex(4);
});
}
@Test
public void testLeft() {
lineEditor.setText("Ja");
lineEditor.setInsertionIndex(2);
lineEditor.left();
Assertions.assertEquals("Ja", lineEditor.getText());
Assertions.assertEquals(1, lineEditor.getInsertionIndex());
lineEditor.left();
Assertions.assertEquals("Ja", lineEditor.getText());
Assertions.assertEquals(0, lineEditor.getInsertionIndex());
lineEditor.left();
Assertions.assertEquals("Ja", lineEditor.getText());
Assertions.assertEquals(0, lineEditor.getInsertionIndex());
}
@Test
public void testRight() {
lineEditor.setText("Ja");
lineEditor.setInsertionIndex(0);
lineEditor.right();
Assertions.assertEquals("Ja", lineEditor.getText());
Assertions.assertEquals(1, lineEditor.getInsertionIndex());
lineEditor.right();
lineEditor.setText("Ja");
Assertions.assertEquals(2, lineEditor.getInsertionIndex());
lineEditor.right();
lineEditor.setText("Ja");
Assertions.assertEquals(2, lineEditor.getInsertionIndex());
}
@Test
public void testDeleteLeft() {
lineEditor.setText("Ja");
lineEditor.setInsertionIndex(0);
lineEditor.deleteLeft();
Assertions.assertEquals("Ja", lineEditor.getText());
Assertions.assertEquals(0, lineEditor.getInsertionIndex());
lineEditor.setInsertionIndex(1);
lineEditor.deleteLeft();
Assertions.assertEquals("a", lineEditor.getText());
Assertions.assertEquals(0, lineEditor.getInsertionIndex());
lineEditor.deleteLeft();
Assertions.assertEquals("a", lineEditor.getText());
Assertions.assertEquals(0, lineEditor.getInsertionIndex());
lineEditor.setText("Ja");
lineEditor.setInsertionIndex(2);
lineEditor.deleteLeft();
Assertions.assertEquals("J", lineEditor.getText());
Assertions.assertEquals(1, lineEditor.getInsertionIndex());
lineEditor.deleteLeft();
Assertions.assertEquals("", lineEditor.getText());
Assertions.assertEquals(0, lineEditor.getInsertionIndex());
lineEditor.deleteLeft();
Assertions.assertEquals("", lineEditor.getText());
Assertions.assertEquals(0, lineEditor.getInsertionIndex());
}
@Test
public void testDeleteRight() {
lineEditor.setText("Ja");
lineEditor.setInsertionIndex(2);
lineEditor.deleteRight();
Assertions.assertEquals("Ja", lineEditor.getText());
Assertions.assertEquals(2, lineEditor.getInsertionIndex());
lineEditor.setInsertionIndex(1);
lineEditor.deleteRight();
Assertions.assertEquals("J", lineEditor.getText());
Assertions.assertEquals(1, lineEditor.getInsertionIndex());
lineEditor.deleteRight();
Assertions.assertEquals("J", lineEditor.getText());
Assertions.assertEquals(1, lineEditor.getInsertionIndex());
lineEditor.setText("Ja");
lineEditor.setInsertionIndex(0);
lineEditor.deleteRight();
Assertions.assertEquals("a", lineEditor.getText());
Assertions.assertEquals(0, lineEditor.getInsertionIndex());
lineEditor.deleteRight();
Assertions.assertEquals("", lineEditor.getText());
Assertions.assertEquals(0, lineEditor.getInsertionIndex());
lineEditor.deleteRight();
Assertions.assertEquals("", lineEditor.getText());
Assertions.assertEquals(0, lineEditor.getInsertionIndex());
}
@Test
public void testInsertString() {
lineEditor.insertString("");
Assertions.assertEquals("", lineEditor.getText());
Assertions.assertEquals(0, lineEditor.getInsertionIndex());
lineEditor.insertString("Java");
Assertions.assertEquals("Java", lineEditor.getText());
Assertions.assertEquals(4, lineEditor.getInsertionIndex());
lineEditor.insertString(" er gøy!");
Assertions.assertEquals("Java er gøy!", lineEditor.getText());
Assertions.assertEquals(12, lineEditor.getInsertionIndex());
lineEditor.setText("Javagøy!");
lineEditor.setInsertionIndex(4);
lineEditor.insertString(" er ");
Assertions.assertEquals("Java er gøy!", lineEditor.getText());
Assertions.assertEquals(8, lineEditor.getInsertionIndex());
lineEditor.setText("er gøy!");
lineEditor.setInsertionIndex(0);
lineEditor.insertString("Java ");
Assertions.assertEquals("Java er gøy!", lineEditor.getText());
Assertions.assertEquals(5, lineEditor.getInsertionIndex());
}
}

View File

@@ -0,0 +1,133 @@
package encapsulation;
import static org.junit.jupiter.api.Assertions.*;
import java.util.Date;
import java.util.Random;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class PersonTest {
private Person person;
@BeforeEach
public void setup() {
person = new Person();
}
private void testInvalidName(String invalidName, String existingName) {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
person.setName(invalidName);
});
Assertions.assertEquals(existingName, person.getName());
}
@Test
void testSetName() throws Exception {
String name = person.getName();
testInvalidName("Ola", name);
testInvalidName("O N", name);
testInvalidName("Ola Mellom Nordmann", name);
testInvalidName("O. Nordmann", name);
Assertions.assertDoesNotThrow(() -> {
person.setName("Espen Askeladd");
});
Assertions.assertEquals("Espen Askeladd", person.getName());
}
@Test
void testSetBirthday() {
long today = new Date().getTime();
long offset = 1000L * 60L * 60L * 24L * 100L; // About 100 days
// Test with incorrect birthday
Assertions.assertThrows(IllegalArgumentException.class, () -> {
Date theFuture = new Date(today + offset);
person.setBirthday(theFuture);
});
// Test with correct birthday
Date thePast = new Date(today - offset);
Assertions.assertDoesNotThrow(() -> {
person.setBirthday(thePast);
});
Assertions.assertEquals(thePast, person.getBirthday());
}
private void testInvalidEmail(String invalidEmail, String existingEmail, Class<? extends Exception> ex) {
Assertions.assertThrows(ex, () -> {
person.setEmail(invalidEmail);
});
Assertions.assertEquals(existingEmail, person.getEmail());
}
private String generateValidDomain() {
Random random = new Random();
int length = random.nextInt(63) + 1;
String validCharacters = "abcdefghijklmnopqrstuvwxyz0123456789";
String domain = "";
for (int currentChar = 0; currentChar < length; currentChar++) {
int character = random.nextInt(36);
domain += validCharacters.substring(character, character + 1);
}
return domain;
}
@Test
void testSetEmail() {
person.setName("Ola Nordmann");
String email = person.getEmail();
testInvalidEmail("ola.nordmann@ntnu", email, IllegalArgumentException.class);
testInvalidEmail("ola.nordmann(at)ntnu.no", email, IllegalArgumentException.class);
testInvalidEmail("espen.askeladd@eventyr.no", email, IllegalArgumentException.class);
Assertions.assertDoesNotThrow(() -> {
person.setEmail("ola.nordmann@ntnu.no");
});
assertEquals("ola.nordmann@ntnu.no", person.getEmail());
}
@Test
public void testExtraCountryTopLevelDomains(){
String[] cTLDs = {"ad", "ae", "af", "ag", "ai", "al", "am", "ao", "aq", "ar", "as", "at", "au", "aw", "ax", "az", "ba", "bb", "bd", "be", "bf", "bg", "bh", "bi", "bj", "bl", "bm", "bn", "bo", "bq", "br", "bs", "bt", "bv", "bw", "by", "bz", "ca", "cc", "cd", "cf", "cg", "ch", "ci", "ck", "cl", "cm", "cn", "co", "cr", "cu", "cv", "cw", "cx", "cy", "cz", "de", "dj", "dk", "dm", "do", "dz", "ec", "ee", "eg", "eh", "er", "es", "et", "fi", "fj", "fk", "fm", "fo", "fr", "ga", "gb", "gd", "ge", "gf", "gg", "gh", "gi", "gl", "gm", "gn", "gp", "gq", "gr", "gs", "gt", "gu", "gw", "gy", "hk", "hm", "hn", "hr", "ht", "hu", "id", "ie", "il", "im", "in", "io", "iq", "ir", "is", "it", "je", "jm", "jo", "jp", "ke", "kg", "kh", "ki", "km", "kn", "kp", "kr", "kw", "ky", "kz", "la", "lb", "lc", "li", "lk", "lr", "ls", "lt", "lu", "lv", "ly", "ma", "mc", "md", "me", "mf", "mg", "mh", "mk", "ml", "mm", "mn", "mo", "mp", "mq", "mr", "ms", "mt", "mu", "mv", "mw", "mx", "my", "mz", "na", "nc", "ne", "nf", "ng", "ni", "nl", "no", "np", "nr", "nu", "nz", "om", "pa", "pe", "pf", "pg", "ph", "pk", "pl", "pm", "pn", "pr", "ps", "pt", "pw", "py", "qa", "re", "ro", "rs", "ru", "rw", "sa", "sb", "sc", "sd", "se", "sg", "sh", "si", "sj", "sk", "sl", "sm", "sn", "so", "sr", "ss", "st", "sv", "sx", "sy", "sz", "tc", "td", "tf", "tg", "th", "tj", "tk", "tl", "tm", "tn", "to", "tr", "tt", "tv", "tw", "tz", "ua", "ug", "um", "us", "uy", "uz", "va", "vc", "ve", "vg", "vi", "vn", "vu", "wf", "ws", "ye", "yt", "za", "zm", "zw"};
String[] invalidCTLDs = {"aa", "ab", "ac", "ah", "aj", "ak", "an", "ap", "av", "ay", "bc", "bk", "bp", "bu", "bx", "cb", "ce", "cj", "cp", "cq", "cs", "ct", "da", "db", "dc", "dd", "df", "dg", "dh", "di", "dl", "dn", "dp", "dq", "dr", "ds", "dt", "du", "dv", "dw", "dx", "dy", "ea", "eb", "ed", "ef", "ei", "ej", "ek", "el", "em", "en", "eo", "ep", "eq", "eu", "ev", "ew", "ex", "ey", "ez", "fa", "fb", "fc", "fd", "fe", "ff", "fg", "fh", "fl", "fn", "fp", "fq", "fs", "ft", "fu", "fv", "fw", "fx", "fy", "fz", "gc", "gj", "gk", "go", "gv", "gx", "gz", "ha", "hb", "hc", "hd", "he", "hf", "hg", "hh", "hi", "hj", "hl", "ho", "hp", "hq", "hs", "hv", "hw", "hx", "hy", "hz", "ia", "ib", "ic", "if", "ig", "ih", "ii", "ij", "ik", "ip", "iu", "iv", "iw", "ix", "iy", "iz", "ja", "jb", "jc", "jd", "jf", "jg", "jh", "ji", "jj", "jk", "jl", "jn", "jq", "jr", "js", "jt", "ju", "jv", "jw", "jx", "jy", "jz", "ka", "kb", "kc", "kd", "kf", "kj", "kk", "kl", "ko", "kq", "ks", "kt", "ku", "kv", "kx", "ld", "le", "lf", "lg", "lh", "lj", "ll", "lm", "ln", "lo", "lp", "lq", "lw", "lx", "lz", "mb", "mi", "mj", "nb", "nd", "nh", "nj", "nk", "nm", "nn", "nq", "ns", "nt", "nv", "nw", "nx", "ny", "oa", "ob", "oc", "od", "oe", "of", "og", "oh", "oi", "oj", "ok", "ol", "on", "oo", "op", "oq", "or", "os", "ot", "ou", "ov", "ow", "ox", "oy", "oz", "pb", "pc", "pd", "pi", "pj", "po", "pp", "pq", "pu", "pv", "px", "pz", "qb", "qc", "qd", "qe", "qf", "qg", "qh", "qi", "qj", "qk", "ql", "qm", "qn", "qo", "qp", "qq", "qr", "qs", "qt", "qu", "qv", "qw", "qx", "qy", "qz", "ra", "rb", "rc", "rd", "rf", "rg", "rh", "ri", "rj", "rk", "rl", "rm", "rn", "rp", "rq", "rr", "rt", "rv", "rx", "ry", "rz", "sf", "sp", "sq", "su", "sw", "ta", "tb", "te", "ti", "tp", "tq", "ts", "tu", "tx", "ty", "ub", "uc", "ud", "ue", "uf", "uh", "ui", "uj", "uk", "ul", "un", "uo", "up", "uq", "ur", "ut", "uu", "uv", "uw", "ux", "vb", "vd", "vf", "vh", "vj", "vk", "vl", "vm", "vo", "vp", "vq", "vr", "vs", "vt", "vv", "vw", "vx", "vy", "vz", "wa", "wb", "wc", "wd", "we", "wg", "wh", "wi", "wj", "wk", "wl", "wm", "wn", "wo", "wp", "wq", "wr", "wt", "wu", "wv", "ww", "wx", "wy", "wz", "xa", "xb", "xc", "xd", "xe", "xf", "xg", "xh", "xi", "xj", "xk", "xl", "xm", "xn", "xo", "xp", "xq", "xr", "xs", "xt", "xu", "xv", "xw", "xx", "xy", "xz", "ya", "yb", "yc", "yd", "yf", "yg", "yh", "yi", "yj", "yk", "yl", "ym", "yn", "yo", "yp", "yq", "yr", "ys", "yu", "yv", "yw", "yx", "yy", "yz", "zb", "zc", "zd", "ze", "zf", "zg", "zh", "zi", "zj", "zk", "zl", "zn", "zo", "zp", "zq", "zr", "zs", "zt", "zu", "zv", "zx", "zy", "zz"};
person.setName("John Doe");
String email = person.getEmail();
for (String cTLD : invalidCTLDs) {
testInvalidEmail("john.doe@ntnu." + cTLD, email, IllegalArgumentException.class);
}
for (String cTLD : cTLDs) {
final String localemail = "john.doe@" + generateValidDomain() + "." + cTLD;
Assertions.assertDoesNotThrow(() -> {
person.setEmail(localemail);
});
Assertions.assertEquals(localemail, person.getEmail());
}
}
@Test
void testSetGender() {
String validGenders = "FM\0";
char gender = person.getGender();
for (char c = '\0'; c < '\uFFFF'; c++) {
if (validGenders.indexOf(c) < 0) {
gender = person.getGender();
final char localc = c;
Assertions.assertThrows(IllegalArgumentException.class, () -> {
person.setGender(localc);
});
Assertions.assertEquals(gender, person.getGender());
}
else {
final char localc = c;
Assertions.assertDoesNotThrow(() -> {
person.setGender(localc);
});
Assertions.assertEquals(localc, person.getGender());
}
}
}
}

View File

@@ -0,0 +1,63 @@
package encapsulation;
import static org.junit.jupiter.api.Assertions.*;
import java.util.Date;
import java.util.Random;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class PersonTest2 {
private Person person;
private static int[]
factors1 = {3, 7, 6, 1, 8, 9, 4, 5, 2},
factors2 = {5, 4, 3, 2, 7, 6, 5, 4, 3, 2};
@BeforeEach
public void setup() {
person = new Person();
}
@SuppressWarnings("deprecation")
@Test
public void testSetSSN() {
person.setBirthday(new Date(94, 0, 1));
person.setGender('M');
Assertions.assertDoesNotThrow(() -> {
person.setSSN("010194111" + generateValid(1, 1, 1, "010194"));
});
assertEquals("01019411156", person.getSSN());
Assertions.assertThrows(Exception.class, () -> {
person.setSSN("010194112" + generateValid(1, 1, 2, "010194"));
});
assertEquals("01019411156", person.getSSN());
Assertions.assertThrows(Exception.class, () -> {
person.setSSN("01019411122");
});
assertEquals("01019411156", person.getSSN());
}
private static String generateValid(int n1, int n2, int n3, String birthday) {
birthday = birthday + n1 + n2 + n3;
int k1 = 0, k2 = 0;
for(int i = 0; i < birthday.length(); i++) {
int num = Character.getNumericValue(birthday.charAt(i));
k1 += factors1[i] * num;
k2 += factors2[i] * num;
}
k1 = 11 - (k1 % 11);
if (k1 == 11) {
k1 = 0;
}
k2 += k1 * factors2[9];
k2 = 11 - (k2 % 11);
if (k2 == 11) {
k2 = 0;
}
return k1 + "" + k2;
}
}

View File

@@ -0,0 +1,113 @@
package encapsulation;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class RPNCalcTest{
private RPNCalc calc;
@BeforeEach
public void setup() {
calc = new RPNCalc();
}
@Test
public void testPush() {
calc.push(1.0);
Assertions.assertEquals(1.0, calc.peek(0));
calc.push(2.0);
Assertions.assertEquals(2.0, calc.peek(0));
calc.push(3.0);
Assertions.assertEquals(3.0, calc.peek(0));
}
@Test
public void testPop() {
calc.push(1.0);
calc.push(2.0);
calc.push(3.0);
Assertions.assertEquals(3.0, calc.peek(0));
Assertions.assertEquals(3.0, calc.pop());
Assertions.assertEquals(2.0, calc.peek(0));
Assertions.assertEquals(2.0, calc.pop());
Assertions.assertEquals(1.0, calc.peek(0));
calc.push(2.0);
Assertions.assertEquals(2.0, calc.peek(0));
Assertions.assertEquals(2.0, calc.pop());
Assertions.assertEquals(1.0, calc.peek(0));
Assertions.assertEquals(1.0, calc.pop());
Assertions.assertEquals(0, calc.getSize());
}
@Test
public void testPeek() {
calc.push(0.0);
calc.push(1.0);
calc.push(2.0);
Assertions.assertEquals(2.0, calc.peek(0));
Assertions.assertEquals(1.0, calc.peek(1));
Assertions.assertEquals(0.0, calc.peek(2));
}
@Test
public void testEmptyStack() {
Assertions.assertEquals(Double.NaN, calc.peek(3));
Assertions.assertEquals(Double.NaN, calc.peek(-1));
}
@Test
public void testGetSize() {
Assertions.assertEquals(0, calc.getSize());
calc.push(1.0);
Assertions.assertEquals(1, calc.getSize());
calc.push(2.0);
Assertions.assertEquals(2, calc.getSize());
}
@Test
public void testAddOperation() {
calc.push(3.0);
calc.push(4.0);
calc.performOperation('+');
Assertions.assertEquals(1, calc.getSize());
Assertions.assertEquals(7.0, calc.peek(0));
}
@Test
public void testSubOperation() {
calc.push(7.0);
calc.push(2.0);
calc.performOperation('-');
Assertions.assertEquals(1, calc.getSize());
Assertions.assertEquals(5.0, calc.peek(0));
}
@Test
public void testMultOperation() {
calc.push(5.0);
calc.push(2.0);
calc.performOperation('*');
Assertions.assertEquals(1, calc.getSize());
Assertions.assertEquals(10.0, calc.peek(0));
}
@Test
public void testDivOperation() {
calc.push(10.0);
calc.push(4.0);
calc.performOperation('/');
Assertions.assertEquals(1, calc.getSize());
Assertions.assertEquals(2.5, calc.peek(0));
}
}

View File

@@ -0,0 +1,159 @@
package encapsulation;
import static org.junit.jupiter.api.Assertions.*;
import java.util.Date;
import java.util.Random;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class VehicleTest {
Vehicle vehicle;
private void checkVehicleState(char vehicleType, char fuelType, String registrationNumber, Vehicle vehicle) {
Assertions.assertEquals(vehicleType, vehicle.getVehicleType());
Assertions.assertEquals(fuelType, vehicle.getFuelType());
Assertions.assertEquals(registrationNumber, vehicle.getRegistrationNumber());
}
private static void checkInvalidConstructor(char vehicleType, char fuelType, String registrationNumber) {
assertThrows(IllegalArgumentException.class, () -> {
new Vehicle(vehicleType, fuelType, registrationNumber);
});
}
private static void checkInvalidsetRegistration(Vehicle vehicle, String originalRegNum, String newRegNum) {
assertThrows(IllegalArgumentException.class, () -> {
vehicle.setRegistrationNumber(newRegNum);
});
assertEquals(originalRegNum, vehicle.getRegistrationNumber());
}
@Test
void testConstructor() {
vehicle = new Vehicle('C', 'D', "BN12345");
checkVehicleState('C', 'D', "BN12345", vehicle);
vehicle = new Vehicle('M', 'E', "EL1234");
checkVehicleState('M', 'E', "EL1234", vehicle);
checkInvalidConstructor('C', 'Y', "BN12345");
checkInvalidConstructor('M', 'H', "HY1234");
checkInvalidConstructor('P', 'D', "BN12345");
checkInvalidConstructor('C', 'G', "A1234");
checkInvalidConstructor('C', 'G', "A12345");
checkInvalidConstructor('C', 'G', "A123456");
checkInvalidConstructor('C', 'G', "A12344");
checkInvalidConstructor('C', 'G', "AÆ12345");
checkInvalidConstructor('C', 'G', "ab12345");
checkInvalidConstructor('C', 'G', "A12345");
checkInvalidConstructor('C', 'G', "A1B12345");
checkInvalidConstructor('M', 'G', "A1234");
checkInvalidConstructor('M', 'G', "A12345");
checkInvalidConstructor('M', 'G', "A123");
checkInvalidConstructor('M', 'G', "AB12345");
checkInvalidConstructor('M', 'G', "ABC1234");
checkInvalidConstructor('M', 'G', "ABC12345");
checkInvalidConstructor('C', 'G', "AÅ1234");
checkInvalidConstructor('C', 'G', "ab1234");
checkInvalidConstructor('C', 'G', "EL12345");
checkInvalidConstructor('C', 'G', "EK12345");
checkInvalidConstructor('C', 'G', "HY12345");
checkInvalidConstructor('C', 'D', "EL12345");
checkInvalidConstructor('C', 'D', "EK12345");
checkInvalidConstructor('C', 'D', "HY12345");
checkInvalidConstructor('C', 'H', "EL12345");
checkInvalidConstructor('C', 'H', "EK12345");
checkInvalidConstructor('C', 'H', "BN12345");
checkInvalidConstructor('C', 'E', "HY12345");
checkInvalidConstructor('C', 'E', "BN12345");
checkInvalidConstructor('M', 'G', "EL1234");
checkInvalidConstructor('M', 'G', "EK1234");
checkInvalidConstructor('M', 'G', "HY1234");
checkInvalidConstructor('M', 'D', "EL1234");
checkInvalidConstructor('M', 'D', "EK1234");
checkInvalidConstructor('M', 'D', "HY1234");
checkInvalidConstructor('M', 'E', "HY1234");
checkInvalidConstructor('M', 'E', "BN1234");
}
@Test
void testSetRegistrationNumber() {
vehicle = new Vehicle('C', 'D', "BN12345");
vehicle.setRegistrationNumber("AB54321");
checkVehicleState('C', 'D', "AB54321", vehicle);
vehicle = new Vehicle('M', 'E', "EK1234");
vehicle.setRegistrationNumber("EL4321");
checkVehicleState('M', 'E', "EL4321", vehicle);
vehicle = new Vehicle('C', 'D', "BN12345");
Assertions.assertThrows(IllegalArgumentException.class, () -> {
vehicle.setRegistrationNumber("AB654321");
});
checkVehicleState('C', 'D', "BN12345", vehicle);
vehicle = new Vehicle('M', 'E', "EL1234");
Assertions.assertThrows(IllegalArgumentException.class, () -> {
vehicle.setRegistrationNumber("HY1234");
});
checkVehicleState('M', 'E', "EL1234", vehicle);
vehicle = new Vehicle('C', 'G', "AB12345");
checkInvalidsetRegistration(vehicle, vehicle.getRegistrationNumber(), "A1234");
checkInvalidsetRegistration(vehicle, vehicle.getRegistrationNumber(), "A12345");
checkInvalidsetRegistration(vehicle, vehicle.getRegistrationNumber(), "AB1234");
checkInvalidsetRegistration(vehicle, vehicle.getRegistrationNumber(), "AB123456");
checkInvalidsetRegistration(vehicle, vehicle.getRegistrationNumber(), "ABC1234");
checkInvalidsetRegistration(vehicle, vehicle.getRegistrationNumber(), "AÆ12345");
checkInvalidsetRegistration(vehicle, vehicle.getRegistrationNumber(), "ab12345");
checkInvalidsetRegistration(vehicle, vehicle.getRegistrationNumber(), "A1B2345");
checkInvalidsetRegistration(vehicle, vehicle.getRegistrationNumber(), "A1234");
checkInvalidsetRegistration(vehicle, vehicle.getRegistrationNumber(), "A12345");
checkInvalidsetRegistration(vehicle, vehicle.getRegistrationNumber(), "AB1234");
checkInvalidsetRegistration(vehicle, vehicle.getRegistrationNumber(), "AB123456");
checkInvalidsetRegistration(vehicle, vehicle.getRegistrationNumber(), "ABC1234");
checkInvalidsetRegistration(vehicle, vehicle.getRegistrationNumber(), "AÆ12345");
checkInvalidsetRegistration(vehicle, vehicle.getRegistrationNumber(), "ab12345");
checkInvalidsetRegistration(vehicle, vehicle.getRegistrationNumber(), "A1B2345");
vehicle = new Vehicle('M', 'G', "AB1234");
checkInvalidsetRegistration(vehicle, vehicle.getRegistrationNumber(), "A1234");
checkInvalidsetRegistration(vehicle, vehicle.getRegistrationNumber(), "A12345");;
checkInvalidsetRegistration(vehicle, vehicle.getRegistrationNumber(), "AB123");
checkInvalidsetRegistration(vehicle, vehicle.getRegistrationNumber(), "AB12345");
checkInvalidsetRegistration(vehicle, vehicle.getRegistrationNumber(), "ABC1234");
checkInvalidsetRegistration(vehicle, vehicle.getRegistrationNumber(), "ABC12345");
checkInvalidsetRegistration(vehicle, vehicle.getRegistrationNumber(), "AÅ1234");
checkInvalidsetRegistration(vehicle, vehicle.getRegistrationNumber(), "ab1234");
vehicle = new Vehicle('C', 'G', "AB12345");
checkInvalidsetRegistration(vehicle, vehicle.getRegistrationNumber(), "EL12345");
checkInvalidsetRegistration(vehicle, vehicle.getRegistrationNumber(), "EK12345");
checkInvalidsetRegistration(vehicle, vehicle.getRegistrationNumber(), "HY12345");
vehicle = new Vehicle('C', 'D', "AB12345");
checkInvalidsetRegistration(vehicle, vehicle.getRegistrationNumber(), "EL12345");
checkInvalidsetRegistration(vehicle, vehicle.getRegistrationNumber(), "EK12345");
checkInvalidsetRegistration(vehicle, vehicle.getRegistrationNumber(), "HY12345");
vehicle = new Vehicle('C', 'H', "HY12345");
checkInvalidsetRegistration(vehicle, vehicle.getRegistrationNumber(), "EL12345");
checkInvalidsetRegistration(vehicle, vehicle.getRegistrationNumber(), "EK12345");
checkInvalidsetRegistration(vehicle, vehicle.getRegistrationNumber(), "BN12345");
vehicle = new Vehicle('C', 'E', "EL12345");
checkInvalidsetRegistration(vehicle, vehicle.getRegistrationNumber(), "HY12345");
checkInvalidsetRegistration(vehicle, vehicle.getRegistrationNumber(), "BN12345");
vehicle = new Vehicle('M', 'G', "AB1234");
checkInvalidsetRegistration(vehicle, vehicle.getRegistrationNumber(), "EL1234");
checkInvalidsetRegistration(vehicle, vehicle.getRegistrationNumber(), "EK1234");
checkInvalidsetRegistration(vehicle, vehicle.getRegistrationNumber(), "HY1234");
vehicle = new Vehicle('M', 'D', "AB1234");
checkInvalidsetRegistration(vehicle, vehicle.getRegistrationNumber(), "EL1234");
checkInvalidsetRegistration(vehicle, vehicle.getRegistrationNumber(), "EK1234");
checkInvalidsetRegistration(vehicle, vehicle.getRegistrationNumber(), "HY1234");
vehicle = new Vehicle('M', 'E', "EK1234");
checkInvalidsetRegistration(vehicle, vehicle.getRegistrationNumber(), "HY1234");
checkInvalidsetRegistration(vehicle, vehicle.getRegistrationNumber(), "BN1234");
}
}

View File

@@ -0,0 +1,67 @@
package interfaces;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class BinaryComputingIteratorTest{
private Iterator<Double> iterator1, iterator2, iteratorShort;
@BeforeEach
public void setup() {
iterator1 = Arrays.asList(0.5, -2.0).iterator();
iterator2 = Arrays.asList(5.0, 3.0).iterator();
iteratorShort = Arrays.asList(5.0).iterator();
}
@Test
public void testMultiplication() {
BinaryComputingIterator binaryIt = new BinaryComputingIterator(iterator1, iterator2, (a, b) -> a * b);
Assertions.assertEquals(2.5, binaryIt.next());
Assertions.assertTrue(binaryIt.hasNext());
Assertions.assertEquals(-6.0, binaryIt.next());
Assertions.assertFalse(binaryIt.hasNext());
}
@Test
public void testAddition() {
BinaryComputingIterator binaryIt = new BinaryComputingIterator(iterator1, iterator2, (a, b) -> a + b);
Assertions.assertEquals(5.5, binaryIt.next());
Assertions.assertTrue(binaryIt.hasNext());
Assertions.assertEquals(1.0, binaryIt.next());
Assertions.assertFalse(binaryIt.hasNext());
}
@Test
public void testShortIterator() {
BinaryComputingIterator binaryIt = new BinaryComputingIterator(iterator1, iteratorShort, (a, b) -> a * b);
Assertions.assertEquals(2.5, binaryIt.next());
Assertions.assertFalse(binaryIt.hasNext());
}
@Test
public void testShortIteratorAndDefault() {
BinaryComputingIterator binaryIt = new BinaryComputingIterator(iterator1, iteratorShort, null, 2.0, (a, b) -> a * b);
Assertions.assertEquals(2.5, binaryIt.next());
Assertions.assertTrue(binaryIt.hasNext());
Assertions.assertEquals(-4.0, binaryIt.next());
Assertions.assertFalse(binaryIt.hasNext());
}
@Test
public void testEmptyIterator() {
BinaryComputingIterator binaryIt = new BinaryComputingIterator(new ArrayList().iterator(), new ArrayList().iterator(), (a, b) -> a * b);
Assertions.assertFalse(binaryIt.hasNext());
}
@Test
public void testEmptyIteratorAndDefault() {
BinaryComputingIterator binaryIt = new BinaryComputingIterator(new ArrayList().iterator(), new ArrayList().iterator(), 1.0, 2.0, (a, b) -> a * b);
Assertions.assertFalse(binaryIt.hasNext());
}
}

View File

@@ -0,0 +1,59 @@
package interfaces;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
public class RPNCalcTest {
private RPNCalc calc;
@BeforeEach
public void setup() {
calc = new RPNCalc();
}
@Test
public void testPerformOperationWithoutOperation() {
Assertions.assertThrows(UnsupportedOperationException.class, () -> {
calc.performOperation('+');
});
}
@Test
public void testPerformOperation() {
calc.addOperator('+', (a, b) -> a * b); // Use "incorrect" definition to filter out cheating
calc.addOperator('l', (a, b) -> a * (a + b));
calc.push(4);
calc.push(3);
calc.performOperation('+');
Assertions.assertEquals(12.0, calc.pop());
Assertions.assertEquals(Double.NaN, calc.pop());
calc.push(4);
calc.push(3);
calc.performOperation('l');
Assertions.assertEquals(28.0, calc.pop());
Assertions.assertEquals(Double.NaN, calc.pop());
}
@Test
public void testAddOperator() {
Assertions.assertTrue(calc.addOperator('+', (a, b) -> a + b));
Assertions.assertTrue(calc.addOperator('-', (a, b) -> a - b));
Assertions.assertFalse(calc.addOperator('+', (a, b) -> a + b));
Assertions.assertFalse(calc.addOperator('-', (a, b) -> a * b));
}
@Test
public void testRemoveOperator() {
calc.addOperator('+', (a, b) -> a + b);
calc.removeOperator('+');
Assertions.assertThrows(UnsupportedOperationException.class, () -> {
calc.performOperation('+');
});
}
}

View File

@@ -0,0 +1,77 @@
package objectstructures;
import static org.junit.Assert.assertThrows;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.DisplayName;
public class CoffeeCupTest {
CoffeeCup cup;
CoffeeCup halfWayFilledCup;
@BeforeEach
public void setup() {
this.cup = new CoffeeCup();
this.halfWayFilledCup = new CoffeeCup(2, 1);
}
@Test
@DisplayName("Test constructor validation")
public void testConstructorValidation() {
assertThrows(IllegalArgumentException.class, () -> new CoffeeCup(-1, -2));
assertThrows(IllegalArgumentException.class, () -> new CoffeeCup(1, -1));
assertThrows(IllegalArgumentException.class, () -> new CoffeeCup(2, 3));
var localCup = new CoffeeCup(3, 2);
}
@Test
@DisplayName("Test getCapacity")
public void testGetCapacity() {
assertEquals(0, cup.getCapacity());
assertEquals(2, halfWayFilledCup.getCapacity());
}
@Test
@DisplayName("Test getCurrentVolume")
public void testGetCurrentVolume() {
assertEquals(0, cup.getCurrentVolume());
assertEquals(1, halfWayFilledCup.getCurrentVolume());
}
@Test
@DisplayName("Test increaseCupSize")
public void testIncreaseCupSize() {
assertEquals(0, cup.getCapacity());
cup.increaseCupSize(3);
assertEquals(3, cup.getCapacity());
cup.increaseCupSize(1.5);
assertEquals(4.5, cup.getCapacity());
cup.increaseCupSize(-1);
assertEquals(4.5, cup.getCapacity());
}
@Test
@DisplayName("Test drinkCoffee")
public void testDrinkCoffee() {
assertEquals(1, halfWayFilledCup.getCurrentVolume());
halfWayFilledCup.drinkCoffee(0.5);
assertEquals(0.5, halfWayFilledCup.getCurrentVolume());
halfWayFilledCup.drinkCoffee(0.5);
assertEquals(0, halfWayFilledCup.getCurrentVolume());
assertThrows(IllegalArgumentException.class, () -> cup.drinkCoffee(0.5));
}
@Test
@DisplayName("Test fillCoffee")
public void testFillCoffee() {
assertEquals(1, halfWayFilledCup.getCurrentVolume());
halfWayFilledCup.fillCoffee(0.5);
assertEquals(1.5, halfWayFilledCup.getCurrentVolume());
halfWayFilledCup.fillCoffee(0.5);
assertEquals(2, halfWayFilledCup.getCurrentVolume());
assertThrows(IllegalArgumentException.class, () -> cup.fillCoffee(0.5));
}
}

View File

@@ -0,0 +1,282 @@
package objectstructures;
import java.util.Arrays;
import java.util.Collection;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.DisplayName;
public class PersonTest {
private Person hallvard, marit, jens, anne;
private void hasChildren(Person person, Collection<Person> children) {
Assertions.assertEquals(children.size(), person.getChildCount());
for (Person child : children) {
boolean found = false;
int i = 0;
while (i < person.getChildCount()) {
if (child == person.getChild(i)) {
found = true;
}
i++;
}
Assertions.assertTrue(found);
}
}
@BeforeEach
public void setup() {
hallvard = new Person("Hallvard", 'M');
marit = new Person("Marit", 'F');
jens = new Person("Jens", 'M');
anne = new Person("Anne", 'F');
}
@Test
@DisplayName("Kvinne kan ikke være far")
public void testFatherException() {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
jens.setFather(marit);
});
Assertions.assertThrows(IllegalArgumentException.class, () -> {
anne.setFather(marit);
});
}
@Test
@DisplayName("Mann kan ikke være mor")
public void testMotherException() {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
jens.setMother(hallvard);
});
Assertions.assertThrows(IllegalArgumentException.class, () -> {
anne.setMother(hallvard);
});
}
@Test
@DisplayName("Mann kan ikke være sin egen far")
public void testSelfFatherException() {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
jens.setFather(jens);
});
}
@Test
@DisplayName("Kvinne kan ikke være sin egen mor")
public void testSelfMotherException() {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
anne.setMother(anne);
});
}
@Test
@DisplayName("Sette farskap med setFather")
public void testSetFather() {
jens.setFather(hallvard);
// Check state of hallvard
Assertions.assertEquals(null, hallvard.getFather());
Assertions.assertEquals(null, hallvard.getMother());
hasChildren(hallvard, Arrays.asList(jens));
//Check state of jens
Assertions.assertEquals(hallvard, jens.getFather());
Assertions.assertEquals(null, jens.getMother());
Assertions.assertEquals(0, jens.getChildCount());
anne.setFather(hallvard);
// Check state of hallvard
Assertions.assertEquals(null, hallvard.getFather());
Assertions.assertEquals(null, hallvard.getMother());
hasChildren(hallvard, Arrays.asList(jens, anne));
//Check state of jens
Assertions.assertEquals(hallvard, jens.getFather());
Assertions.assertEquals(null, jens.getMother());
Assertions.assertEquals(0, jens.getChildCount());
//Check state of anne
Assertions.assertEquals(hallvard, anne.getFather());
Assertions.assertEquals(null, anne.getMother());
Assertions.assertEquals(0, anne.getChildCount());
}
@Test
@DisplayName("Sette farskap med addChild")
public void testFatherAddChild() {
hallvard.addChild(jens);
// Check state of hallvard
Assertions.assertEquals(null, hallvard.getFather());
Assertions.assertEquals(null, hallvard.getMother());
hasChildren(hallvard, Arrays.asList(jens));
//Check state of jens
Assertions.assertEquals(hallvard, jens.getFather());
Assertions.assertEquals(null, jens.getMother());
Assertions.assertEquals(0, jens.getChildCount());
hallvard.addChild(anne);
// Check state of hallvard
Assertions.assertEquals(null, hallvard.getFather());
Assertions.assertEquals(null, hallvard.getMother());
hasChildren(hallvard, Arrays.asList(jens, anne));
//Check state of jens
Assertions.assertEquals(hallvard, jens.getFather());
Assertions.assertEquals(null, jens.getMother());
Assertions.assertEquals(0, jens.getChildCount());
//Check state of anne
Assertions.assertEquals(hallvard, anne.getFather());
Assertions.assertEquals(null, anne.getMother());
Assertions.assertEquals(0, anne.getChildCount());
}
@Test
@DisplayName("Sette morskap med setMother")
public void testSetMother() {
jens.setMother(marit);
// Check state of marit
Assertions.assertEquals(null, marit.getFather());
Assertions.assertEquals(null, marit.getMother());
hasChildren(marit, Arrays.asList(jens));
//Check state of jens
Assertions.assertEquals(null, jens.getFather());
Assertions.assertEquals(marit, jens.getMother());
Assertions.assertEquals(0, jens.getChildCount());
anne.setMother(marit);
// Check state of marit
Assertions.assertEquals(null, marit.getFather());
Assertions.assertEquals(null, marit.getMother());
hasChildren(marit, Arrays.asList(jens, anne));
//Check state of jens
Assertions.assertEquals(null, jens.getFather());
Assertions.assertEquals(marit, jens.getMother());
Assertions.assertEquals(0, jens.getChildCount());
//Check state of anne
Assertions.assertEquals(null, anne.getFather());
Assertions.assertEquals(marit, anne.getMother());
Assertions.assertEquals(0, anne.getChildCount());
}
@Test
@DisplayName("Sette morskap med addChild")
public void testMotherAddChild() {
marit.addChild(jens);
// Check state of marit
Assertions.assertEquals(null, marit.getFather());
Assertions.assertEquals(null, marit.getMother());
hasChildren(marit, Arrays.asList(jens));
//Check state of jens
Assertions.assertEquals(null, jens.getFather());
Assertions.assertEquals(marit, jens.getMother());
Assertions.assertEquals(0, jens.getChildCount());
marit.addChild(anne);
// Check state of marit
Assertions.assertEquals(null, marit.getFather());
Assertions.assertEquals(null, marit.getMother());
hasChildren(marit, Arrays.asList(jens, anne));
//Check state of jens
Assertions.assertEquals(null, jens.getFather());
Assertions.assertEquals(marit, jens.getMother());
Assertions.assertEquals(0, jens.getChildCount());
//Check state of anne
Assertions.assertEquals(null, anne.getFather());
Assertions.assertEquals(marit, anne.getMother());
Assertions.assertEquals(0, anne.getChildCount());
}
@Test
@DisplayName("Endre far med setFather")
public void testChangeFatherSetFather() {
anne.setFather(jens);
// Check state of anne
Assertions.assertEquals(jens, anne.getFather());
// Check state of jens
hasChildren(jens, Arrays.asList(anne));
anne.setFather(hallvard);
// Check state of anne
Assertions.assertEquals(hallvard, anne.getFather());
// Check state of jens
Assertions.assertEquals(0, jens.getChildCount());
// Check state of hallvard
hasChildren(hallvard, Arrays.asList(anne));
}
@Test
@DisplayName("Endre far med addChild")
public void testChangeFatherAddChild() {
jens.addChild(anne);
// Check state of anne
Assertions.assertEquals(jens, anne.getFather());
// Check state of jens
hasChildren(jens, Arrays.asList(anne));
hallvard.addChild(anne);
// Check state of anne
Assertions.assertEquals(hallvard, anne.getFather());
// Check state of jens
Assertions.assertEquals(0, jens.getChildCount());
// Check state of hallvard
hasChildren(hallvard, Arrays.asList(anne));
}
@Test
@DisplayName("Endre morskap med setMother")
public void testChangeMotherSetMother() {
jens.setMother(anne);
// Check state of jens
Assertions.assertEquals(anne, jens.getMother());
// Check state of anne
hasChildren(anne, Arrays.asList(jens));
jens.setMother(marit);
// Check state of jens
Assertions.assertEquals(marit, jens.getMother());
// Check state of anne
Assertions.assertEquals(0, anne.getChildCount());
// Check state of marit
hasChildren(marit, Arrays.asList(jens));
}
@Test
@DisplayName("Endre morskap med addChild")
public void testChangeMotherAddChild() {
anne.addChild(jens);
// Check state of jens
Assertions.assertEquals(anne, jens.getMother());
// Check state of anne
hasChildren(anne, Arrays.asList(jens));
marit.addChild(jens);
// Check state of jens
Assertions.assertEquals(marit, jens.getMother());
// Check state of anne
Assertions.assertEquals(0, anne.getChildCount());
// Check state of marit
hasChildren(marit, Arrays.asList(jens));
}
}

View File

@@ -0,0 +1,15 @@
package setupcheck;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.*;
class SimpleClassTest {
@Test
public void testSimpleClassGetsValue() {
SimpleClass c = new SimpleClass(5);
assertEquals(c.getMyVal(), 5);
}
}

View File

@@ -0,0 +1,111 @@
package stateandbehavior;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class LineEditorTest {
private LineEditor lineEditor;
private void checkEditorContent(String s) {
Assertions.assertEquals(s, lineEditor.toString());
int pos = s.indexOf('|');
Assertions.assertEquals(s.substring(0, pos) + s.substring(pos + 1), lineEditor.getText());
Assertions.assertEquals(pos, lineEditor.getInsertionIndex());
}
@BeforeEach
public void setup() {
lineEditor = new LineEditor();
}
@Test
public void testContstructor() {
checkEditorContent("|");
}
@Test
public void testSetters() {
lineEditor.setText("Hello World!");
checkEditorContent("|Hello World!");
lineEditor.setInsertionIndex(5);
checkEditorContent("Hello| World!");
}
@Test
public void testInsertStringAtEnd() {
lineEditor.insertString("");
checkEditorContent("|");
lineEditor.insertString("Java");
checkEditorContent("Java|");
lineEditor.insertString(" er gøy!");
checkEditorContent("Java er gøy!|");
}
@Test
public void testInsertStringMiddle() {
lineEditor.setText("Javagøy!");
lineEditor.setInsertionIndex(4);
lineEditor.insertString(" er ");
checkEditorContent("Java er |gøy!");
}
@Test
public void testInsertStringAtBeginning() {
lineEditor.setText("er gøy!");
lineEditor.setInsertionIndex(0);
lineEditor.insertString("Java ");
checkEditorContent("Java |er gøy!");
}
@Test
public void testLeft() {
lineEditor.left();
checkEditorContent("|");
lineEditor.setText("J");
lineEditor.setInsertionIndex(1);
checkEditorContent("J|");
lineEditor.left();
checkEditorContent("|J");
}
@Test
public void testRight() {
lineEditor.right();
checkEditorContent("|");
lineEditor.setText("J");
lineEditor.setInsertionIndex(0);
checkEditorContent("|J");
lineEditor.right();
checkEditorContent("J|");
}
@Test
public void testDeleteLeft() {
lineEditor.deleteLeft();
checkEditorContent("|");
lineEditor.insertString("J");
lineEditor.deleteLeft();
checkEditorContent("|");
lineEditor.insertString("Java");
lineEditor.setInsertionIndex(2);
checkEditorContent("Ja|va");
lineEditor.deleteLeft();
checkEditorContent("J|va");
}
@Test
public void testDeleteRight() {
lineEditor.deleteRight();
checkEditorContent("|");
lineEditor.insertString("J");
lineEditor.setInsertionIndex(0);
lineEditor.deleteRight();
checkEditorContent("|");
lineEditor.insertString("Java");
lineEditor.setInsertionIndex(2);
checkEditorContent("Ja|va");
lineEditor.deleteRight();
checkEditorContent("Ja|a");
}
}

View File

@@ -0,0 +1,203 @@
package stateandbehavior;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class RectangleTest {
private Rectangle rect;
@BeforeEach
protected void setUp() {
rect = new Rectangle();
}
/**
* Check all values related to a {@link Rectangle}.
*
* @param rect The rectangle to check
* @param minX The expected minimum x value of rect
* @param minY The expected minimum y value of rect
* @param maxX The expected maximum x value of rect
* @param maxY The expected maximum y value of rect
* @param w The expected width of rect
* @param h The expected height of rect
*/
private void assertValues(Rectangle rect, int minX, int minY, int maxX, int maxY, int w, int h) {
Assertions.assertEquals(minX, rect.getMinX());
Assertions.assertEquals(minY, rect.getMinY());
Assertions.assertEquals(maxX, rect.getMaxX());
Assertions.assertEquals(maxY, rect.getMaxY());
Assertions.assertEquals(w, rect.getWidth());
Assertions.assertEquals(h, rect.getHeight());
}
/**
* Check that a rectangle is empty
*
* @param rect The rectangle to check
*/
private void assertEmpty(Rectangle rect) {
Assertions.assertTrue(rect.isEmpty());
Assertions.assertFalse(rect.contains(0, 0));
assertValues(rect, 0, 0, 0, 0, 0, 0);
}
@Test
public void testConstructor() {
assertEmpty(rect);
}
private void testAdd(Rectangle rect, int x, int y, Boolean expected) {
boolean result = rect.add(x, y);
if (expected != null) {
Assertions.assertEquals(expected.booleanValue(), result);
}
Assertions.assertFalse(rect.isEmpty());
Assertions.assertTrue(rect.contains(x, y));
}
@Test
public void testAddXYToEmpty() {
int x = 13, y = -27;
testAdd(rect, x, y, true);
assertValues(rect, x, y, x, y, 1, 1);
}
@Test
public void testAddXY() {
int x1 = 13, y1 = -27;
int x2 = -11, y2 = 23;
int x3 = 15, y3 = 33;
// Add (x1, y1) to the rect, and check that all values are updated accordingly
testAdd(rect, x1, y1, true);
assertValues(rect, x1, y1, x1, y1, 1, 1);
// Add (x2, y2) and check that rect is updated accordingly. Note how we check
// for minimum and maximum x an y values in the points.
testAdd(rect, x2, y2, true);
int minX1X2 = Math.min(x1, x2), minY1Y2 = Math.min(y1, y2);
int maxX1X2 = Math.max(x1, x2), maxY1Y2 = Math.max(y1, y2);
assertValues(rect, minX1X2, minY1Y2, maxX1X2, maxY1Y2, maxX1X2 - minX1X2 + 1, maxY1Y2 - minY1Y2 + 1);
// Add (x3, y3) and check that rect is updated accordingly.
testAdd(rect, x3, y3, true);
int minX1X2X3 = Math.min(minX1X2, x3), minY1Y2Y3 = Math.min(minY1Y2, y3);
int maxX1X2X3 = Math.max(maxX1X2, x3), maxY1Y2Y3 = Math.max(maxY1Y2, y3);
assertValues(rect, minX1X2X3, minY1Y2Y3, maxX1X2X3, maxY1Y2Y3, maxX1X2X3 - minX1X2X3 + 1, maxY1Y2Y3 - minY1Y2Y3 + 1);
}
@Test
public void testAddSameXY() {
int x = 13, y = -27;
testAdd(rect, x, y, true);
assertValues(rect, x, y, x, y, 1, 1);
testAdd(rect, x, y, false);
assertValues(rect, x, y, x, y, 1, 1);
}
@Test
public void testAddRectangleToEmpty() {
int x1 = 13, y1 = -27;
int x2 = -11, y2 = 23;
// Create a rectangle and fill it with some points. Assert that this rect is correct.
Rectangle rect = new Rectangle();
testAdd(rect, x1, y1, true);
assertValues(rect, x1, y1, x1, y1, 1, 1);
testAdd(rect, x2, y2, true);
int minX1X2 = Math.min(x1, x2), minY1Y2 = Math.min(y1, y2);
int maxX1X2 = Math.max(x1, x2), maxY1Y2 = Math.max(y1, y2);
assertValues(rect, minX1X2, minY1Y2, maxX1X2, maxY1Y2, maxX1X2 - minX1X2 + 1, maxY1Y2 - minY1Y2 + 1);
// Add rect to this.rect, and check that this.rect is updated accordingly.
Assertions.assertTrue(this.rect.add(rect));
assertValues(this.rect, minX1X2, minY1Y2, maxX1X2, maxY1Y2, maxX1X2 - minX1X2 + 1, maxY1Y2 - minY1Y2 + 1);
}
@Test
public void testAddRectangle() {
// Add a point to this.rect
int x1 = 13, y1 = -27;
int x2 = -11, y2 = 23;
int x3 = 15, y3 = 33;
testAdd(this.rect, x3, y3, true);
assertValues(this.rect, x3, y3, x3, y3, 1, 1);
// Create a new rect, add two points, and check correctness
Rectangle rect = new Rectangle();
testAdd(rect, x1, y1, true);
assertValues(rect, x1, y1, x1, y1, 1, 1);
testAdd(rect, x2, y2, true);
int minX1X2 = Math.min(x1, x2), minY1Y2 = Math.min(y1, y2);
int maxX1X2 = Math.max(x1, x2), maxY1Y2 = Math.max(y1, y2);
assertValues(rect, minX1X2, minY1Y2, maxX1X2, maxY1Y2, maxX1X2 - minX1X2 + 1, maxY1Y2 - minY1Y2 + 1);
// Add rect to this.rect, and check correctness
Assertions.assertTrue(this.rect.add(rect));
int minX1X2X3 = Math.min(minX1X2, x3), minY1Y2Y3 = Math.min(minY1Y2, y3);
int maxX1X2X3 = Math.max(maxX1X2, x3), maxY1Y2Y3 = Math.max(maxY1Y2, y3);
assertValues(this.rect, minX1X2X3, minY1Y2Y3, maxX1X2X3, maxY1Y2Y3, maxX1X2X3 - minX1X2X3 + 1, maxY1Y2Y3 - minY1Y2Y3 + 1);
}
@Test
public void testAddSameRectangle() {
// Create a rectangle from two points, and check correctness
int x1 = 13, y1 = -27;
int x2 = -11, y2 = 23;
Rectangle rect = new Rectangle();
testAdd(rect, x1, y1, true);
assertValues(rect, x1, y1, x1, y1, 1, 1);
testAdd(rect, x2, y2, true);
int minX1X2 = Math.min(x1, x2), minY1Y2 = Math.min(y1, y2);
int maxX1X2 = Math.max(x1, x2), maxY1Y2 = Math.max(y1, y2);
assertValues(rect, minX1X2, minY1Y2, maxX1X2, maxY1Y2, maxX1X2 - minX1X2 + 1, maxY1Y2 - minY1Y2 + 1);
// First time rectangle is added, add should return true and this.rect be updated
Assertions.assertTrue(this.rect.add(rect));
assertValues(this.rect, minX1X2, minY1Y2, maxX1X2, maxY1Y2, maxX1X2 - minX1X2 + 1, maxY1Y2 - minY1Y2 + 1);
// Second time, add should return false and this.rect should remain the same.
Assertions.assertFalse(this.rect.add(rect));
assertValues(this.rect, minX1X2, minY1Y2, maxX1X2, maxY1Y2, maxX1X2 - minX1X2 + 1, maxY1Y2 - minY1Y2 + 1);
}
@Test
public void testUnion() {
int x1 = 13, y1 = -27;
int x2 = -11, y2 = 23;
int x3 = 15, y3 = 33;
int x4 = 17, y4 = -33;
// Add values to this.rect and check correctness
testAdd(this.rect, x3, y3, true);
assertValues(this.rect, x3, y3, x3, y3, 1, 1);
testAdd(this.rect, x4, y4, true);
int minX3X4 = Math.min(x3, x4), minY3Y4 = Math.min(y3, y4);
int maxX3X4 = Math.max(x3, x4), maxY3Y4 = Math.max(y3, y4);
assertValues(this.rect, minX3X4, minY3Y4, maxX3X4, maxY3Y4, maxX3X4 - minX3X4 + 1, maxY3Y4 - minY3Y4 + 1);
// Create a new rect, and check correctness
Rectangle rect = new Rectangle();
testAdd(rect, x1, y1, true);
assertValues(rect, x1, y1, x1, y1, 1, 1);
testAdd(rect, x2, y2, true);
int minX1X2 = Math.min(x1, x2), minY1Y2 = Math.min(y1, y2);
int maxX1X2 = Math.max(x1, x2), maxY1Y2 = Math.max(y1, y2);
assertValues(rect, minX1X2, minY1Y2, maxX1X2, maxY1Y2, maxX1X2 - minX1X2 + 1, maxY1Y2 - minY1Y2 + 1);
// Take the union (both ways), and check that both
int minX = Math.min(minX1X2, minX3X4), minY = Math.min(minY1Y2, minY3Y4);
int maxX = Math.max(maxX1X2, maxX3X4), maxY = Math.max(maxY1Y2, maxY3Y4);
Rectangle union1 = this.rect.union(rect);
assertValues(union1, minX, minY, maxX, maxY, maxX - minX + 1, maxY - minY + 1);
assertValues(this.rect, minX3X4, minY3Y4, maxX3X4, maxY3Y4, maxX3X4 - minX3X4 + 1, maxY3Y4 - minY3Y4 + 1);
assertValues(rect, minX1X2, minY1Y2, maxX1X2, maxY1Y2, maxX1X2 - minX1X2 + 1, maxY1Y2 - minY1Y2 + 1);
Rectangle union2 = rect.union(this.rect);
assertValues(union2, minX, minY, maxX, maxY, maxX - minX + 1, maxY - minY + 1);
assertValues(this.rect, minX3X4, minY3Y4, maxX3X4, maxY3Y4, maxX3X4 - minX3X4 + 1, maxY3Y4 - minY3Y4 + 1);
assertValues(rect, minX1X2, minY1Y2, maxX1X2, maxY1Y2, maxX1X2 - minX1X2 + 1, maxY1Y2 - minY1Y2 + 1);
}
}

View File

@@ -0,0 +1,128 @@
package stateandbehavior;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class StopWatchTest {
private StopWatch stopWatch;
@BeforeEach
public void beforeEach() {
stopWatch = new StopWatch();
}
@Test
public void testConstructor() {
Assertions.assertFalse(stopWatch.isStarted());
Assertions.assertFalse(stopWatch.isStopped());
Assertions.assertEquals(0, stopWatch.getTicks());
Assertions.assertEquals(-1, stopWatch.getTime());
Assertions.assertEquals(-1, stopWatch.getLapTime());
Assertions.assertEquals(-1, stopWatch.getLastLapTime());
}
@Test
public void testTicksWithoutStart() {
stopWatch.tick(1);
Assertions.assertEquals(-1, stopWatch.getTime());
Assertions.assertEquals(1, stopWatch.getTicks());
stopWatch.tick(4);
Assertions.assertEquals(-1, stopWatch.getTime());
Assertions.assertEquals(5, stopWatch.getTicks());
}
@Test
public void testStartTickStop() {
stopWatch.start();
Assertions.assertEquals(0, stopWatch.getTime());
Assertions.assertEquals(0, stopWatch.getTicks());
Assertions.assertTrue(stopWatch.isStarted());
Assertions.assertFalse(stopWatch.isStopped());
stopWatch.tick(3);
Assertions.assertEquals(3, stopWatch.getTime());
Assertions.assertEquals(3, stopWatch.getTicks());
Assertions.assertTrue(stopWatch.isStarted());
Assertions.assertFalse(stopWatch.isStopped());
stopWatch.tick(5);
Assertions.assertEquals(8, stopWatch.getTime());
Assertions.assertEquals(8, stopWatch.getTicks());
Assertions.assertTrue(stopWatch.isStarted());
Assertions.assertFalse(stopWatch.isStopped());
stopWatch.stop();
Assertions.assertEquals(8, stopWatch.getTime());
Assertions.assertEquals(8, stopWatch.getTicks());
Assertions.assertTrue(stopWatch.isStarted());
Assertions.assertTrue(stopWatch.isStopped());
}
@Test
public void testTickStartTickStopTick() {
stopWatch.tick(2);
Assertions.assertEquals(-1, stopWatch.getTime());
Assertions.assertEquals(2, stopWatch.getTicks());
Assertions.assertFalse(stopWatch.isStarted());
Assertions.assertFalse(stopWatch.isStopped());
stopWatch.start();
Assertions.assertEquals(0, stopWatch.getTime());
Assertions.assertEquals(2, stopWatch.getTicks());
Assertions.assertTrue(stopWatch.isStarted());
Assertions.assertFalse(stopWatch.isStopped());
stopWatch.tick(3);
Assertions.assertEquals(3, stopWatch.getTime());
Assertions.assertEquals(5, stopWatch.getTicks());
Assertions.assertTrue(stopWatch.isStarted());
Assertions.assertFalse(stopWatch.isStopped());
stopWatch.tick(5);
Assertions.assertEquals(8, stopWatch.getTime());
Assertions.assertEquals(10, stopWatch.getTicks());
Assertions.assertTrue(stopWatch.isStarted());
Assertions.assertFalse(stopWatch.isStopped());
stopWatch.stop();
Assertions.assertEquals(8, stopWatch.getTime());
Assertions.assertEquals(10, stopWatch.getTicks());
Assertions.assertTrue(stopWatch.isStarted());
Assertions.assertTrue(stopWatch.isStopped());
stopWatch.tick(3);
Assertions.assertEquals(8, stopWatch.getTime());
Assertions.assertEquals(13, stopWatch.getTicks());
Assertions.assertTrue(stopWatch.isStarted());
Assertions.assertTrue(stopWatch.isStopped());
}
@Test
public void testLaps() {
stopWatch.start();
Assertions.assertEquals(0, stopWatch.getTime());
Assertions.assertEquals(0, stopWatch.getLapTime());
Assertions.assertEquals(-1, stopWatch.getLastLapTime());
stopWatch.tick(3);
Assertions.assertEquals(3, stopWatch.getTime());
Assertions.assertEquals(3, stopWatch.getLapTime());
Assertions.assertEquals(-1, stopWatch.getLastLapTime());
stopWatch.lap();
Assertions.assertEquals(3, stopWatch.getTime());
Assertions.assertEquals(0, stopWatch.getLapTime());
Assertions.assertEquals(3, stopWatch.getLastLapTime());
stopWatch.tick(5);
Assertions.assertEquals(8, stopWatch.getTime());
Assertions.assertEquals(5, stopWatch.getLapTime());
Assertions.assertEquals(3, stopWatch.getLastLapTime());
stopWatch.stop();
Assertions.assertEquals(8, stopWatch.getTime());
Assertions.assertEquals(0, stopWatch.getLapTime());
Assertions.assertEquals(5, stopWatch.getLastLapTime());
}
}