Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • adil.obol/lecture_code
  • ii/inf101/24v/students/lecture_code
  • Anders.Tokje/lecture_code
  • antoine.hureau/lecture_code_300124
  • Rein.Landmark/lecture-code-1-30-24
  • Simon.Alvsaker/lecture_code
  • stine.kristoffersen/lecture_code
  • Tyra.Eide/lecture_code
8 results
Show changes
Showing
with 1071 additions and 0 deletions
package lecture6_interface;
public class UsePokemon {
public static void main(String[] args) {
Pokemon mew = new Pokemon("Mew", 6, new RandomAttack());
Pokemon snorLax = new Pokemon("SnorLax", 12, new SleepAttack());
snorLax.healthPoints=1000;
IPokemon attacker = snorLax;
IPokemon defender = new FirePokemon("CharMander", 12);
}
}
package lecture7_collections;
import static java.util.Comparator.nullsLast;
import java.util.Comparator;
/**
* This Comparator Compares author first, and if author is equal title is used to break ties.
* null elements are always after Book objects
*
* @author Martin Vatshelle
*
*/
public class AuthorThenTitle implements Comparator<Book>{
@Override
public int compare(Book o1, Book o2) {
//Create a Comparator that does not handle null
//the following two lines are equivalent
//Comparator<Book> authorComp = new CompareAuthor();
Comparator<Book> authorComp = Comparator.comparing((b)->b.author);
//Create a second Comparator for comparing on title
//the following two lines are equivalent
//Comparator<Book> titleComp = new CompareTitle();
Comparator<Book> titleComp = Comparator.comparing((b)->b.title);
//the method thenComparing combines two Comparators
//if the title is the same, then author is compared instead
Comparator<Book> compNoNull = authorComp.thenComparing(titleComp);
//the method nullsLast creates a Comparator that handles null first
//if either object is null, the null is always last
//if no objects is null, the compNoNull is used
Comparator<Book> comp = nullsLast(compNoNull);
return comp.compare(o1, o2);
}
}
package lecture7_collections;
import java.util.Comparator;
import static java.util.Comparator.comparing;
import static java.util.Comparator.nullsLast;
public class Book implements Comparable<Book>{
//feltvariabler
String title;
String author;
public Book(String title, String author){
this.title = title;
this.author = author;
}
@Override
public String toString() {
return title+" by "+author;
}
@Override
public boolean equals(Object obj) {
if(this == obj) {
return true;
}
if(obj instanceof Book) {
Book toCompare = (Book)obj;
if(this.author.equals(toCompare.author) && this.title.equals(toCompare.title)) {
return true;
}
}
return false;
}
@Override
public int compareTo(Book o) {
return this.author.compareTo(o.author);
}
}
package lecture7_collections;
import java.util.Comparator;
/**
* This comparator compares the field author in the Book class
* This Comparator does not handle null objects.
*
* @author Martin Vatshelle
*
*/
public class CompareAuthor implements Comparator<Book> {
@Override
public int compare(Book o1, Book o2) {
return o1.author.compareTo(o2.author);
}
}
package lecture7_collections;
import java.util.Comparator;
/**
* This Comparator compares the title of books
* Null elements are always after Book Objects
*
* @author Martin Vatshelle
*
*/
public class CompareTitle implements Comparator<Book>{
@Override
public int compare(Book o1, Book o2) {
if(o1==null && o2==null) {
return 0;
}
if(o1==null) {
return 1;
}
if(o2==null) {
return -1;
}
return o1.title.compareTo(o2.title);
}
}
package lecture7_collections;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
public class Library {
List<Book> books;
public Library() {
books = new LinkedList<Book>();
}
void add(Book book) {
books.add(book);
}
boolean hasBook(Book book) {
return books.contains(book);
}
public static void main(String[] args) {
Library myBooks = new Library();
System.out.println(myBooks.books);
Book myBook = new Book("Objects","Martin");
myBooks.add(myBook);
System.out.println(myBooks.books);
Book myFavorite = new Book("INF101", "Sondre");
System.out.println(myBooks.hasBook(myFavorite));
myBooks.add(myFavorite);
System.out.println(myBooks.hasBook(myFavorite));
System.out.println(myBooks.books);
Book wanted = new Book("Objects","Martin");
System.out.println(myBooks.hasBook(wanted));
myBooks.add(new Book("Dyr", "Tommy"));
myBooks.add(new Book("Klima", "Susanne"));
myBooks.add(new Book("Biler", "Ida"));
myBooks.add(new Book("INF102", "Martin"));
myBooks.books.add(null);
System.out.println(myBooks.books);
//sorting using Comparable
if(!myBooks.books.contains(null)) {
Collections.sort(myBooks.books); //will not work if the list contains null
}
else {
Collections.sort(myBooks.books,Comparator.nullsLast(Comparator.naturalOrder()));
}
System.out.println(myBooks.books);
//sorting using Comparator
Collections.sort(myBooks.books, new CompareTitle());
System.out.println(myBooks.books);
//sorting using Comparator breaking ties
Collections.sort(myBooks.books, new AuthorThenTitle());
System.out.println(myBooks.books);
}
}
package lecture7_collections;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Random;
public class UseCollections {
public static void main(String[] args) {
Collection<Integer> tall = getCollection(10);
System.out.println(tall);
Integer smallest = Collections.min(tall);
System.out.println(smallest);
ArrayList<Integer> listOfNumbers = new ArrayList<>(tall);
Collections.sort(listOfNumbers);
System.out.println(listOfNumbers);
int count = Collections.frequency(tall, smallest);
System.out.println(smallest+" occur "+count+" times.");
}
private static Collection<Integer> getCollection(int numElem) {
ArrayList<Integer> list = new ArrayList<>();
Random rand = new Random();
for(int i=0; i<numElem; i++) {
list.add(rand.nextInt(10));
}
return list;
}
}
package lecture8_encapsulation;
public class TrafficLight {
private boolean red;
private boolean yellow;
private boolean green;
public TrafficLight() {
this(true,false,false);
}
public TrafficLight(boolean red, boolean yellow, boolean green) {
if(!isValid(red, yellow, green)) {
throw new IllegalArgumentException("Can not construct traffic light with illegal state Red: "+red+" Yellow: "+yellow+" Green: "+green);
}
this.red = red;
this.yellow = yellow;
this.green = green;
}
static boolean isValid(boolean red, boolean yellow, boolean green) {
if(green && (red || yellow)) {
return false;
}
if(!red && !yellow && !green) {
return false;
}
return true;
}
public boolean isRed() {
return red;
}
public boolean isYellow() {
return yellow;
}
public boolean isGreen() {
return green;
}
public void next() {
if(red) {
if(!yellow) { //case 1
yellow = true;
}
else { //case 2
red=false;
yellow=false;
green=true;
}
}else {
if(green) { //case 3
green = false;
yellow=true;
}else { //case 4
yellow=false;
red=true;
}
}
}
}
package lecture8_encapsulation;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TrafficLightVisualizer extends JPanel{
private static final long serialVersionUID = 1L;
TrafficLight state = new TrafficLight();
public TrafficLightVisualizer() {
view();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new BasicStroke(10));
drawRed(g);
drawYellow(g);
drawGreen(g);
}
void drawRed(Graphics g) {
g.setColor(Color.RED);
drawCircleByCenter(g, getLightSize()*1/2, state.isRed());
}
void drawYellow(Graphics g) {
g.setColor(Color.YELLOW);
drawCircleByCenter(g, getLightSize()*3/2, state.isYellow());
}
void drawGreen(Graphics g) {
g.setColor(Color.GREEN);
drawCircleByCenter(g, getLightSize()*5/2, state.isGreen());
}
int getlightRadius() {
return getLightSize()/2-5;
}
int getLightSize() {
return Math.min(getWidth(),getHeight()/3);
}
void drawCircleByCenter(Graphics g, int y,boolean fill){
int radius = getlightRadius();
int x = getWidth()/2;
if(fill) {
g.fillOval(x-radius, y-radius, 2*radius, 2*radius);
}else {
g.drawOval(x-radius, y-radius, 2*radius, 2*radius);
}
}
/** Run the terminal GUI in a window frame.
* @throws InterruptedException */
public void view() {
JFrame frame = new JFrame("TrafficLight");
frame.setSize(200,600);
//Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(this);
//frame.pack();
frame.setVisible(true);
}
public void view(TrafficLight light) {
this.state = light;
repaint();
}
void run() {
for(int i=0; i<100; i++) {
state.next();
repaint();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) throws InterruptedException {
TrafficLightVisualizer light = new TrafficLightVisualizer();
light.view();
light.run();
}
}
package lecture8_encapsulation;
public class UseTrafficLight {
public static void main(String[] args) {
TrafficLight light = new TrafficLight();
TrafficLightVisualizer viewer = new TrafficLightVisualizer();
light.next();
//light.green = true; //not allowed with private fields
try {
light = new TrafficLight(true,true,true);
}catch(IllegalArgumentException e){
System.out.println("You created an illegal traffic light, default value will be used.");
light = new TrafficLight();
}
viewer.view(light);
// try {
// viewer.run();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
}
}
package lecture_18_repetition;
public class AirLock implements IAirLock{
private Door inner;
private Door outer;
public AirLock() {
inner = new Door();
outer = new Door();
}
Door getInner() {
return inner;
}
@Override
public void openInner() {
openDoor(inner);
}
@Override
public void openOuter() {
openDoor(outer);
}
private void openDoor(Door door) {
if(!inner.isOpen() && !outer.isOpen())
door.open();
else
System.out.println("Can not open both at the same time");
}
@Override
public void closeInner() {
inner.close();
}
@Override
public void closeOuter() {
outer.close();
}
@Override
public boolean innerIsOpen() {
return inner.isOpen();
}
@Override
public boolean outerIsOpen() {
return outer.isOpen();
}
@Override
public void lockInner() {
inner.lock();
}
@Override
public void unLockInner() {
inner.unLock();
}
@Override
public void lockOuter() {
outer.lock();
}
@Override
public void unLockOuter() {
outer.unLock();
}
public static void main(String[] args) {
AirLock doors = new AirLock();
doors.openOuter();
doors.getInner().open();
}
}
package lecture_18_repetition;
public class Door {
private boolean isOpen;
private boolean isLocked;
public void open() {
if(!isLocked)
isOpen = true;
}
public boolean isOpen() {
return isOpen;
}
public void close() {
isOpen=false;
}
public void lock() {
if(!isOpen)
isLocked=true;
}
public void unLock() {
isLocked = false;
}
}
package lecture_18_repetition;
/**
* An AirLock is a set of two doors where only one door be open at the time.
* We call the two doors inner and outer door.
*
* In addition each door has a lock, a locked door can not be opened before it is unlocked.
*
* @author Martin Vatshelle
*/
public interface IAirLock {
/** Opens the inner door if it is unlocked and it is allowed to open. */
public void openInner();
/** Opens the outer door if it is unlocked and it is allowed to open. */
public void openOuter();
/** Closes inner door if not already closed. */
public void closeInner();
/** Closes outer door if not already closed */
public void closeOuter();
/** @return true if innerDoor is open, false otherwise */
public boolean innerIsOpen();
/** @return true if outerDoor is open, false otherwise */
public boolean outerIsOpen();
/** locks the inner door if it is closed */
public void lockInner();
/** unlocks the inner door if it is locked */
public void unLockInner();
/** locks the outer door if it is closed */
public void lockOuter();
/** unlocks the outer door if it is locked */
public void unLockOuter();
}
package lecture_19_inheritance;
/**
* Class for storing various types of clothing;
* @author mva021
*
* This type of Object mainly stores information with brand, size and type being examples.
* Such variables are called field variables or instance variables.
* The collection of field variables is called the state of the Object
* These variables all should have get methods, and could have set methods if you want to be able to change the property.
* Brand typically don't change, unless you buy cheap clothing and replace the labels with proper brands in order to earn some extra bucks.
* The important part of a State is those field variables that can change.
*
* Which field variables can change in an object of this class?
*/
public class Clothing {
private String brand;
private int size;
private boolean isDirty;
private String type;
/**
* Constructor is called once for each time you want to make a new clothing item.
* Ideally all properties are set to reasonable default values in the constructor.
* In lecture we did not get the time to set all properties properly.
* @param brand
* @param size
* @param type
*/
public Clothing(String brand, int size, String type) {
this.brand = brand;
this.size = size;
//should probably check that input is a valid type.
//in a bigger application we should probably make type an Object on its own
//so we could have a better control that it was a proper clothingType rather than any string
this.type = type;
this.isDirty = false; //assume new clothing are clean?
}
public String getType() {
return this.type;
}
public String getBrand() {
return brand;
}
public int getSize() {
return this.size;
}
/**
* Method called by a "Person" object when jumpingInMuddyPuddle() method is activated
* Changes the state of this object, i.e. the field variable isDirty
*/
public void makeDirty(){
isDirty = true;
}
/**
* Method called by e.g. the "WashingMachine" object or "Maid" object
* Changes the state of this object, i.e. the field variable isDirty
*/
public void makeClean(){
isDirty = false;
}
/**
* Method used by the drawers, shelves e.g. to check if the item can be placed
* @return
*/
public boolean isDirty() {
return isDirty;
}
/**
* Method called by the "WashingMachine" object
* This is a method that changes the state of the Object by changing the field variable size.
*/
public void shrink() {
size = size-1;
}
}
package lecture_19_inheritance;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class Drawer implements IStorage{
int height;
int width;
int depth;
Collection<Clothing> clothes;
public Drawer(int width, int depth, int height) {
clothes = new ArrayList<Clothing>();
}
public int getHeight(){
return this.height;
}
public int getWidth() {
return width;
}
public int getDepth() {
return depth;
}
public boolean add(Clothing clothing) {
if(canAdd(clothing)) {
clothes.add(clothing);
return true;
}else {
return false;
}
}
/**
* Drawers should only contain clean clothing, no shoes allowed in drawers.
*/
public boolean canAdd(Clothing item) {
if(item.isDirty())
return false;
if(item.getType().equals("Shoes"))
return false;
return true;
}
public boolean remove(Clothing item) {
if(clothes.contains(item))
{
clothes.remove(item);
return true;
}
else {
return false;
}
}
}
package lecture_19_inheritance;
/**
* IStorage space represents a place to put various clothing items.
* Shelf, Drawer and Bar was discussed in lecture.
* LaundryBin, PileOnFloor and Hook could be other classes to be added later
* @author mva021
*/
public interface IStorage {
/**
* Gets the height of the storage space, can be used to check if an item fits inside.
* @return
*/
public int getHeight();
/**
* Gets the width of the storage space, can be used to check if an item fits inside.
* @return
*/
public int getWidth();
/**
* Gets the depth of the storage space, can be used to check if an item fits inside.
* @return
*/
public int getDepth();
/**
* Places an Clothing object in this storage space
* @param clothing - The item to place in the Wardrobe
* @return true if the clothing can be added, false otherwise
*/
public boolean add(Clothing clothing);
/**
* Checks if a clothing fulfills the requirements for being placed.
* Dirty clothing should not end up in the shelves, but may end up in a LaundryBin
* Socks should not end up in shelves (unless they are in a Box which is placed in a Shelf)
* @param item an Clothing item
* @return true if the clothing can be added, false otherwise
*/
public boolean canAdd(Clothing item) ;
/**
* Tries to remove an item of clothing from the Wardrobe.
*
* @param item The clothing item to remove
* @return true if the item was found and removed, false otherwise.
*/
public boolean remove(Clothing item) ;
}
package lecture_19_inheritance;
import java.util.ArrayList;
import java.util.Collection;
public class Shelf implements IStorage{
int height;
int width;
int depth;
Collection<Clothing> clothes;
public Shelf(int width, int depth, int height) {
this.height = height;
this.width = width;
this.depth = depth;
clothes = new ArrayList<Clothing>();
}
public int getHeight(){
return this.height;
}
public int getWidth() {
return width;
}
public int getDepth() {
return depth;
}
public boolean add(Clothing clothing) {
if(canAdd(clothing)) {
clothes.add(clothing);
return true;
}else {
return false;
}
}
/**
* Shelves should only contain clean clothing.
* Socks should not be placed on shelves
*/
public boolean canAdd(Clothing item) {
if(item.isDirty())
return false;
if(item.getType().equals("Socks"))
return false;
return true;
}
public boolean remove(Clothing item) {
if(clothes.contains(item))
{
clothes.remove(item);
return true;
}
else {
return false;
}
}
public static void main(String[] args) {
Shelf shelf = new Shelf(60,40,30);
if(shelf.add(new Clothing("Levis", 20,"Jeans")))
System.out.println("La den p� en hylle!");
else
System.out.println("Kunne ikke legge den p� hyllen");
}
}
package lecture_19_inheritance;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Collections;
public class SortedListAbstract extends AbstractList<Integer>{
ArrayList<Integer> list;
public SortedListAbstract() {
list = new ArrayList<>();
}
@Override
public Integer get(int index) {
return list.get(index);
}
@Override
public int size() {
return list.size();
}
@Override
public Integer set(int index, Integer element) {
int num = list.set(index, element);
Collections.sort(list);
return num;
}
@Override
public void add(int index, Integer element) {
list.add(index, element);
Collections.sort(list);
}
@Override
public boolean remove(Object o) {
return list.remove(o);
}
}
package lecture_19_inheritance;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class SortedListComposition{
//fields
ArrayList<Integer> list;
public SortedListComposition() {
list = new ArrayList<Integer>();
}
public Integer get(int index) {
return list.get(index);
}
public boolean add(Integer e) {
list.add(e);
Collections.sort(list);
return true;
}
//This code is already done
public int size() {
return list.size();
}
public boolean isEmpty() {
return list.isEmpty();
}
public boolean contains(Object o) {
return list.contains(o);
}
public Iterator<Integer> iterator() {
return list.iterator();
}
public Object[] toArray() {
return list.toArray();
}
public <T> T[] toArray(T[] a) {
return list.toArray(a);
}
public boolean remove(Object o) {
return list.remove(o);
}
public boolean containsAll(Collection<?> c) {
return list.containsAll(c);
}
public boolean addAll(Collection<? extends Integer> c) {
list.addAll(c);
Collections.sort(list);
return true;
}
public boolean addAll(int index, Collection<? extends Integer> c) {
list.addAll(index,c);
Collections.sort(list);
return true;
}
public boolean removeAll(Collection<?> c) {
return list.removeAll(c);
}
public boolean retainAll(Collection<?> c) {
return list.retainAll(c);
}
public void clear() {
list.clear();
}
public Integer set(int index, Integer element) {
return list.set(index, element);
}
public void add(int index, Integer element) {
list.add(index,element);
Collections.sort(list);
}
public Integer remove(int index) {
return list.remove(index);
}
public int indexOf(Object o) {
return list.indexOf(o);
}
public int lastIndexOf(Object o) {
return list.lastIndexOf(o);
}
public ListIterator<Integer> listIterator() {
return list.listIterator();
}
public ListIterator<Integer> listIterator(int index) {
return list.listIterator(index);
}
public List<Integer> subList(int fromIndex, int toIndex) {
return subList(fromIndex, toIndex);
}
public String toString() {
return list.toString();
}
}
package lecture_19_inheritance;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
public class SortedListInheritance extends ArrayList<Integer>{
@Override
public boolean add(Integer e) {
super.add(e);
Collections.sort(this);
return true;
}
}