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 694 additions and 0 deletions
package lecture_19_inheritance;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class UseSortedList {
public static void main(String[] args) {
//List<Integer> numbers = new ArrayList<Integer>();
//List<Integer> numbers = new SortedListInheritance();
SortedListComposition numbers = new SortedListComposition();
//List<Integer> numbers = new SortedListAbstract();
Random rand = new Random();
for(int i=0; i<10; i++) {
numbers.add(rand.nextInt(100));
System.out.println(numbers);
}
}
}
package lecture_19_inheritance;
import java.util.ArrayList;
import java.util.List;
public class Wardrobe {
private List<IStorage> storage;
public Wardrobe() {
storage = new ArrayList<IStorage>();
}
/**
* Installs a new shelf in this Wardrobe
* @param width how wide the shelf is
* @param depth how deep the shelf is
* @param height how high the shelf is
*/
public void BuildShelf(int width, int depth, int height) {
storage.add(new Shelf(width,depth,height));
}
/**
* Installs a new drawer in this Wardrobe
* @param width how wide the drawer is
* @param depth how deep the drawer is
* @param height how high the drawer is
*/
public void BuildDrawer() {
storage.add(new Drawer(60,60,15));
}
/**
* Adds an item of clothing to this wardrobe
* @param item the clothing to add
* @return true if there was a space for this item and this item was successfully added, false otherwise
*/
public boolean put(Clothing item){
for(IStorage place : storage) {
if(place.add(item)) {
return true;
}
}
return false;
}
/**
* Takes out an item from the wardrobe
* @param item the item wanted
* @return true if item was found and removed, false otherwise
*/
public boolean remove(Clothing item) { //changed name to remove the name get was not very clear
for(IStorage place : storage) {
if(place.remove(item)) {
return true;
}
}
return false;
}
/**
* A method to build an sample Wardrobe (a bit modest to be a dream wardrobe...)
* A method similar to this one should probably be made such that the user can give user input
* @return A Wardrobe ready to store Clothing objects
*/
public static Wardrobe buildDreamWardrobe() {
Wardrobe myWardrobe = new Wardrobe();
for(int i=1;i<=10;i++) {
myWardrobe.BuildShelf(60,60,30);
}
return myWardrobe;
}
/**
* Just a test that this works, should probably make JUnit tests instead of main method
* @param args
*/
public static void main(String[] args) {
Wardrobe myWardrobe = Wardrobe.buildDreamWardrobe();
System.out.println(myWardrobe.storage.size());
}
}
package lecture_20_exams.corona;
import java.time.LocalDate;
import java.util.ArrayList;
/**
* This class represents the death tolls related to covid-19 reported by a country.
* Deaths are reported one day at the time.
*
* In order to use this data with an existing framework for generating plots
* we need to be able to output this data in ArrayLists
*
* @author Martin Vatshelle - martin.vatshelle@uib.no
*
*/
public interface ICoronaData {
/**
* Returns the dates on which coronaDeaths was reported for this data set(country).
* These dates shall be reported in order, the earliest day first and the most recent date last.
* @return An ArrayList of dates
*/
public ArrayList<LocalDate> getDates();
/**
* Each day a certain number of deaths is reported, this method returns all reported numbers so far.
* The order of the numbers will be the same order as the dates returned by getDates()
* @return an ArrayList of daily death count for each day
*/
public ArrayList<Integer> getDailyDeaths();
/**
* Each ICoronaData series represents a country
* @return name of the country
*/
public String getCountryName();
/**
* The population will be a positive number
* @return the population (number of people) of the country
*/
public int getPopulation();
/**
* For each day return the total number of deaths up until and including that day
* @return an ArrayList containing the cumulative sum of deaths
*/
public ArrayList<Integer> cumulativeDeaths();
/**
* As large countries are expected to have more deaths than small countries,
* a good measure of how hard hit a country is could be how many deaths per million inhabitants
* For each day compute how many deaths (up til and including this day) per million the country has.
*
* Example:
* If there is 2 million people and 5 deaths you should return 2.5
* If there is 3.5 million people and 7 deaths you should return 2
*
* @return a list containing for each day how many deaths there are per million people
*/
public ArrayList<Double> deathsPerMillion();
}
package lecture_20_exams.library;
public class Book {
String title;
String author;
public Book(String title, String author) {
this.title = title;
this.author = author;
}
}
package lecture_20_exams.library;
import java.util.ArrayList;
public class Library{
ArrayList<Book> books = new ArrayList<Book>();
Library(){
//add books to the library
books.add(new Book("Effective Java", "Joshua Bloch"));
books.add(new Book("Clean Code", "Robert Martin"));
books.add(new Book("Head First Design Patterns", "Elisabeth Robson"));
}
/**
* Checks if the library has the book and prints a message
* @param book
*/
public void hasBook(Book book) {
if(books.contains(book))
System.out.println("Yes I can read this over summer!");
else
System.out.println("Oh no, I will not be an Java expert!");
}
public static void main(String[] args) {
Library UiBLib = new Library();
Book wanted = new Book("Clean Code", "Robert Martin");
UiBLib.hasBook(wanted);
}
}
package lecture_20_exams.music;
import java.util.List;
/**
* This class contains two different methods for sorting
*
* @author Martin Vatshelle
*/
public class MusicSorter {
/**
* Sorts the list according to the alphabetic order of Song::getArtistName()
* @param music - the list of songs to be sorted
*/
public static void sortByArtist(List<Song> music) {
//TODO: implement this
}
/**
* Sorts the list according to the Date of Song::getReleaseDate()
* @param music - the list of songs to be sorted
*/
public static void sortByReleaseDate(List<Song> music) {
//TODO: implement this
}
}
\ No newline at end of file
package lecture_20_exams.music;
import java.util.Date;
/**
* This class describes a song
* @author Martin Vatshelle
*/
public class Song {
private String artist;
private String title;
private String genre;
private Date releaseDate;
public Song(String artist, String title, String genre, Date releaseDate) {
this.artist = artist;
this.title = title;
this.genre = genre;
this.releaseDate = releaseDate;
}
public String getArtist() {
return artist;
}
public String getTitle() {
return title;
}
public String getGenre() {
return genre;
}
public Date getReleaseDate() {
return releaseDate;
}
}
package lecture_20_exams.scrabble;
public class Scrabble {
/**
* This method is used by the game Scrabble where the goal is to rearrange
* some of the given letters into a word.
* A letter in Scrabble is always upper case, this method accepts both upper and lower case letters
* and considers e.g. a lower case 'a' equal to an upper case 'A'
* You may assume that all letters in input are valid letters in the English alphabet.
*
* @param letters - the letters you have to your disposal
* @param word - the word you are trying to form
* @return true if it is possible to form the word by rearranging the letters, false otherwise
*/
public static boolean canMake(String letters, String word) {
letters = letters.toUpperCase();
word = word.toUpperCase();
for(Character c:word.toCharArray()) {
if(!letters.contains(c.toString())) {
return false;
}
}
return true;
}
}
\ No newline at end of file
package lecture_20_exams.scrabble;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
public class ScrabbleTest {
@Test
void testCanMakeEksamen(){
assertTrue(Scrabble.canMake("SKAMENE", "EKSAMEN"));
assertTrue(Scrabble.canMake("skaMENE", "EKSAMEN"));
assertTrue(Scrabble.canMake("SKAMENE", "eksAMEN"));
}
@Test
void testCanNotMakeFerie(){
assertFalse(Scrabble.canMake("SKAMENE", "FERIE"));
}
}
package lecture_9_mutability_iterate;
/**
* This class stores the dimensions of a picture frame
*
* @author Martin Vatshelle
*
*/
public class Frame {
private Rectangle inner;
private Rectangle outer;
public Frame(Rectangle inner, Rectangle outer) {
if(inner.getHeight()>outer.getHeight())
throw new IllegalArgumentException("Inner frame can not be higher than outer frame.");
if(inner.getWidth()>outer.getWidth())
throw new IllegalArgumentException("Inner frame can not be wider than outer frame.");
this.inner = inner;
this.outer = outer;
}
Rectangle getInner() {
return inner;
}
Rectangle getOuter() {
return outer;
}
}
package lecture_9_mutability_iterate;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class FrameVisualizer extends JPanel{
private static final long serialVersionUID = 1L;
Frame pictureFrame;
public FrameVisualizer(Frame frame) {
this.pictureFrame = frame;
view();
}
public static void show(Frame frame) {
FrameVisualizer fv = new FrameVisualizer(frame);
fv.view(frame);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new BasicStroke(10));
drawRectangle(g2, pictureFrame.getOuter(),Color.BLACK);
drawRectangle(g2, pictureFrame.getInner(),Color.WHITE);
}
void drawRectangle(Graphics g, Rectangle rectangle,Color color){
int x = (getWidth()-rectangle.getWidth())/2;
int y = (getHeight()-rectangle.getHeight())/2;
g.setColor(color);
g.fillRoundRect(x, y, rectangle.getWidth(), rectangle.getHeight(), 10, 10);
}
/** Run the terminal GUI in a window frame.
* @throws InterruptedException */
public void view() {
JFrame frame = new JFrame("Frame");
int width = Math.max(200, this.pictureFrame.getOuter().getWidth()+20);
int height = Math.max(600, this.pictureFrame.getOuter().getHeight()+20);
frame.setSize(width,height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(this);
frame.setVisible(true);
}
public void view(Frame frame) {
this.pictureFrame = frame;
repaint();
}
}
package lecture_9_mutability_iterate;
import java.util.Iterator;
public class Range implements Iterable<Integer>{
private int start;
private int slutt;
private int step;
public int getStart() {
return start;
}
public int getSlutt() {
return slutt;
}
public int getStep() {
return step;
}
Range(int start, int slutt, int step){
this.start = start;
this.slutt = slutt;
this.step = step;
}
Range(int start, int slutt){
this(start,slutt,1);
}
@Override
public Iterator<Integer> iterator() {
return new RangeIterator(this);
}
@Override
public String toString() {
return "From: "+start+" to: "+slutt+" with steps of "+step;
}
public static Iterable<Integer> range(int start, int slutt, int step){
return new Range(start,slutt,step);
}
public static Iterable<Integer> range(int start, int slutt){
return new Range(start,slutt);
}
}
package lecture_9_mutability_iterate;
import java.util.Iterator;
public class RangeIterator implements Iterator<Integer> {
private Range range;
private int current;
public RangeIterator(Range range) {
this.range = range;
current = range.getStart();
}
@Override
public boolean hasNext() {
if(range.getStep()>=0) {
return current<=range.getSlutt();
}
else {
return current>=range.getSlutt();
}
}
@Override
public Integer next() {
int value = current;
current = current+range.getStep();
return value;
}
}
package lecture_9_mutability_iterate;
/**
* This interface describes the properties of a rectangle
*
* @author Martin Vatshelle
*
*/
public interface Rectangle {
/**
* @return The height of this rectangle, should be greater than 0
*/
int getHeight();
/**
* @return The width of this rectangle, should be greater than 0
*/
int getWidth();
}
package lecture_9_mutability_iterate;
public class RectangleImmutable implements Rectangle{
private int height;
private int width;
public RectangleImmutable(int height,int width) {
if(height<=0 || width<=0)
throw new IllegalArgumentException("Height and width must be positive");
this.height = height;
this.width = width;
}
@Override
public int getHeight() {
return height;
}
@Override
public int getWidth() {
return width;
}
}
package lecture_9_mutability_iterate;
public class RectangleMutable implements Rectangle{
private int height;
private int width;
public RectangleMutable(int height,int width) {
if(height<=0 || width<=0)
throw new IllegalArgumentException("Height and width must be positive");
this.height = height;
this.width = width;
}
@Override
public int getHeight() {
return height;
}
@Override
public int getWidth() {
return width;
}
public void setHeight(int height) {
if(height<=0)
throw new IllegalArgumentException("Height must be positive");
this.height = height;
}
public void setWidth(int width) {
if(width<=0)
throw new IllegalArgumentException("Width must be positive");
this.width = width;
}
}
package lecture_9_mutability_iterate;
public class UseFrame {
public static void main(String[] args) {
RectangleMutable outer = new RectangleMutable(400, 300);
RectangleMutable inner = new RectangleMutable(340, 240);
Frame frame = new Frame(inner, outer);
inner.setHeight(440);
FrameVisualizer fv = new FrameVisualizer(frame);
}
}
package lecture_9_mutability_iterate;
import static lecture_9_mutability_iterate.Range.range;
public class UseRange {
public static void main(String[] args) {
Range range = new Range(1,10,1);
System.out.println(range);
RangeIterator iter = new RangeIterator(range);
while(iter.hasNext()) {
System.out.println(iter.next());
}
for(int i : range) {
System.out.print(i+" ");
}
System.out.println();
for(int i : new Range(1,20,2)) {
System.out.print(i+" ");
}
System.out.println();
for(int i : range(1,20,2)) {
System.out.print(i+" ");
}
System.out.println();
for(int i : range(7,12)) {
System.out.print(i+" ");
}
System.out.println();
for(int i : range(20,12,-1)) {
System.out.print(i+" ");
}
}
}
package lecture_9_mutability_iterate;
public class UseRectangle {
public static void main(String[] args) {
RectangleMutable rect = new RectangleMutable(3,5);
System.out.println(rect.getHeight());
//rect.height = -7; not allowed for private variable
//rect.setHeight(-7);//throws Exception
System.out.println(rect.getHeight());
}
}
package lecture11_testing;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.lang.reflect.Executable;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.util.function.Supplier;
import org.junit.jupiter.api.Test;
class testWeekDay {
@Test
void testMonday() {
LocalDate day = LocalDate.parse("2024-02-26");
DayOfWeek output = WeekDay.dayOfWeek(day);
assertEquals(DayOfWeek.MONDAY, output);
}
@Test
void testTuesday() {
LocalDate day = LocalDate.parse("2024-02-27");
DayOfWeek output = WeekDay.dayOfWeek(day);
assertEquals(DayOfWeek.TUESDAY, output);
}
@Test
void testNull() {
assertThrows(NullPointerException.class, () -> WeekDay.dayOfWeek(null));
assertTrue(5==5, "Math does not know 5=5");
}
}