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
Commits on Source (17)
Showing
with 858 additions and 0 deletions
# Lecture Code
This repository contains all files we use/make during lectures.
After each lecture we will update the project with the relevant files.
## How do I keep my local changes when new lecture notes are added to this file?
If you make changes to this repo, there might become conflicts if both you and the lecturer have changed the same files, and you then try to pull these changes to update your clone of the repo.
It all depends on what you intend to do with the code:
* [I want to make changes to the code and store these in gitlab.](#1-create-a-separate-project-with-changes)
* [I want to make changes to the code but only store them locally.](#2-use-pull-and-manually-deal-with-conflicts)
* [I want to make changes to the code but not store them.](#3-delete-the-clone-and-re-clone)
* [I don't want to make changes to the code.](#4-dont-make-changes)
### 1. Create a separate project with changes
1. Fork and clone or directly clone this repo.
2. Create your own project that is intended for changes. This can be a repo on gitlab that you clone, or it can be just a local file if you don't intend on storing it on gitlab.
3. Copy over the files you want from your clone of the lecture_code-repo, and paste them into the change-repo. You can push these freely if you created a repo.
4. When you want to update your lecture_code repo, use the command ``git pull`` in your terminal to pull new changes from the lecture_code repo. **If you created your own repo**, go into this repo on gitlab and press the button that says "Update fork" first.
5. Copy over the update files you want into your change-repo. You now have no conflicts and get to keep your own changes without problem.
### 2. Use pull and manually deal with conflicts.
**If you want to push your changes to gitlab, use the previous method. This method will make it hard to do so.**
The previous method used the command ``git pull``. No conflicts arose, because no changes had been made to the repo. These were kept in a seperate project. **If you don't intend on pushing your changes to git, you can save yourself the trouble of copying files by using ``git pull`` and then manually dealing with the conflicts.** When you pull files that cause conflict, you will have to do one of two things first:
#### Commit or stash
**Commiting** should be familiar by now. This is what we do before we can push any changes to our gitlab repo.
1. **If you forked this repo**, go into your repo on gitlab and press the button that says "Update fork" first.
2. Save all the files you made changes to locally in you IDE.
3. Use the command ``git add .`` in your terminal to "stage" the changes. (Most IDEs have built in functionality to stage changes as well.)
4. Use the command ``git commit -m "YOUR COMMENT HERE"`` to commit the changes. **DO NOT PUSH**. This may cause a lot of issues. If you want to push changes, use the method above.
5. Use the command ``git pull`` to get the changes from the cloned repo. Conflicts might arise here, and you have to manually choose if you want to keep one version of the file or both versions.
**Stashing** means "putting away" you local changes so you can work on other things and then get these changes back when you need them. This method essentially does the same as commiting.
1. **If you forked this repo**, go into your repo on gitlab and press the button that says "Update fork" first.
2. Save all files you made changes to locally in you IDE.
3. Use the command ``git stash`` in your terminal to stash away the changes. Your project will revert back to the last commit, and your changes will temporarily disappear.
4. Use the command ``git pull`` to get the changes from the cloned repo.
5. Use the command ``git stash pop`` to reinstate your local changes. Conflicts might arise here, and you have to manually choose if you want to keep one version of the file or both versions. **DO NOT PUSH**. This may cause a lot of issues. If you want to push changes, use the method above.
### 3. Delete the clone and re-clone
**If you don't feel the need to keep your changes to the lecture code**, you can simply delete your clone whenever new updates are added. Then, you can clone the project over again and take it from there.
### 4. Don't make changes
**If you don't intend on making any changes to the lecture code**, but you want to have a local save, there will be no conflict issues and you can just use ``git pull`` in your terminal to update your clone (or use method 3).
package lecture10_gui;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JPanel;
public class SampleView extends JPanel{
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g.drawRect(50, 50, 20, 30);
g2.drawRect(100, 100, 70, 70);
}
}
package lecture10_gui;
import javax.swing.JFrame;
public class UseGraphics {
public static void main(String[] args) {
JFrame frame = new JFrame("My GUI app");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,500);
frame.add(new SampleView());
frame.setLocation(500, 100);
frame.setVisible(true);
}
}
package lecture11_testing;
import java.time.DayOfWeek;
import java.time.LocalDate;
public class WeekDay {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
System.out.println(today);
DayOfWeek weekDay = dayOfWeek(today);
}
public static DayOfWeek dayOfWeek(LocalDate today) {
if(today==null)
throw new IllegalArgumentException("input can not be null");
return today.getDayOfWeek();
}
}
package lecture12_generics;
public class DifferentPair<T,V> {
T x;
V y;
public DifferentPair(T x, V y) {
this.x = x;
this.y = y;
}
T getX(){
return x;
}
V getY() {
return y;
}
public static void main(String[] args) {
DifferentPair<String,String> p = new DifferentPair<>("Hei", "INF101");
String x1 = p.getX();
DifferentPair<Integer,Integer> p2 = new DifferentPair<Integer,Integer>(7,23);
int x2 = p2.getX();
DifferentPair<String, Integer> p3 = new DifferentPair<>(new String("Hei"),101);
String x3 = p3.getX();
Integer y3 = p3.getY();
System.out.println(x3);
}
}
package lecture12_generics;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class MaxFinder {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
for(int i=0; i<100; i++) {
list.add(i);
}
Collections.shuffle(list);
int max = getMax(list);
System.out.println(max);
}
private static <T extends Comparable<? super T>> T getMax(List<T> list) {
T max = list.get(0);
for(T i : list) {
if(max.compareTo(i)<0) {
max = i;
}
}
return max;
}
}
package lecture12_generics;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* This class looks through an array to find
* the most common element
*
* @author Martin Vatshelle - martin.vatshelle@uib.no
*
*/
public class MostCommonFinder {
public static void main(String[] args) {
String[] votes = new String[] {"yes","no","no","yes","no","yes","no"};
String majority = findMajorityGeneric(votes);
System.out.println("Voting gave: "+majority);
Integer[] guess = new Integer[]{7,9,3,5,7,8,5,5};
int bestGuess = findMajorityGeneric(guess);
System.out.println("Best guess is: "+bestGuess);
}
private static int findMajority(Integer[] array) {
Integer bestAnswer = null;
int numOccurences = 0;
for(Integer num : array) {
List<Integer> list = Arrays.asList(array);
int count = Collections.frequency(list,num);
if(count>numOccurences) {
bestAnswer = num;
numOccurences = count;
}
}
return bestAnswer;
}
private static String findMajority(String[] array) {
String bestAnswer = null;
int numOccurences = 0;
for(String element : array) {
int count = frequency(element,array);
if(count>numOccurences) {
bestAnswer = element;
numOccurences=count;
}
}
return bestAnswer;
}
private static int frequency(String element, String[] array) {
int count=0;
for(String s : array) {
if(s.equals(element)) {
count++;
}
}
return count;
}
static <T> T findMajorityGeneric(T[] array) {
T bestAnswer = null;
int numOccurences = 0;
for(T num : array) {
List<T> list = Arrays.asList(array);
int count = Collections.frequency(list,num);
if(count>numOccurences) {
bestAnswer = num;
numOccurences = count;
}
}
return bestAnswer;
}
//not a good idea
private static Object findMajority(Object[] array) {
return null;
}
}
package lecture12_generics;
public class Pair<T> {
T x;
T y;
public Pair(T x, T y) {
this.x = x;
this.y = y;
}
void swap() {
T temp = x;
x = y;
y = temp;
}
T getX(){
return x;
}
// int sum() { //not possible to use +
// return x+y;
// }
public static void main(String[] args) {
Pair<String> p = new Pair<String>("Hei", "INF101");
String x1 = p.getX();
Pair<Integer> p2 = new Pair<Integer>(7,23);
int x2 = p2.getX();
Pair<Object> p3 = new Pair<>(new String("Hei"),101);
p3.swap();
Object x3 = p3.getX();
//String text3 = (String)x3; avoid this
System.out.println(x3);
}
}
package lecture14;
public interface IShoppingItem {
/**
* Each ShoppingItem must have a unique name
*
* @return the name of this ShoppingItem
*/
public String getName();
/**
* Returns the price of this ShoppingItem
* @return
*/
public double getPrice();
}
package lecture14;
import java.time.LocalDate;
import java.util.List;
public interface IShoppingList extends Iterable<IShoppingItem>{
/**
* Returns a list of all items you need to buy.
* The order of items on this list is irrelevant.
* Multiple items to shop for should occur multiple times on the list.
*
* E.g. If you have 3 apples on your shopping list
* the list this method returns should contain 3 apples.
*
* @return a list of all items to buy
*/
public List<IShoppingItem> getAllItems();
/**
* Adds an item to this list.
* If item is not a valid ShoppingItem this method should throw an Exception.
*
* @param item - the item to add
* @throws IllegalArgumentException if item is null or item.name is blank
*/
public void add(IShoppingItem item);
/**
* Returns the number of items on this shopping list.
*
* @return the number of items on the shopping list
*/
public int numItems();
/**
* This gives the date this ShoppingList was created
* @return a date
*/
public LocalDate getDate();
/**
* This gives the total sum of the price for all items in the list
* @return
*/
public double totalPrice();
/**
* This methods checks how many items on the list has a given name.
*
* If you have "Apple" 3 times on your list you should return 3
*
* @param itemName - the name of the item to count
* @return the number of items with the given name
*/
public int getItemCount(String itemName);
/**
* This method removes all items that cost more than a certain limit.
*
* @param priceLimit items above this limit gets removed
* @return the number of items removed
*/
public int removeExpensiveItems(double priceLimit);
}
package lecture14;
public class ShoppingItem implements IShoppingItem {
String name;
double price;
public ShoppingItem(String name, double price) {
this.name = name;
this.price = price;
}
@Override
public String getName() {
return name;
}
@Override
public double getPrice() {
return price;
}
@Override
public boolean equals(Object obj) {
if(obj instanceof ShoppingItem) {
ShoppingItem item = (ShoppingItem) obj;
return this.getName().equals(item.getName());
}
return false;
};
}
package lecture14;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
public class ShoppingList implements IShoppingList {
private ArrayList<IShoppingItem> shoppingList;
private LocalDate createdDate;
//Constructor
public ShoppingList(LocalDate date) {
shoppingList = new ArrayList<IShoppingItem>();
createdDate = date;
}
//Methods
@Override
public Iterator<IShoppingItem> iterator() {
return shoppingList.iterator();
}
@Override
public List<IShoppingItem> getAllItems() {
return Collections.unmodifiableList(shoppingList);
}
@Override
public void add(IShoppingItem item) {
if(item==null || item.getName().isBlank())
throw new IllegalArgumentException("Invalid item");
shoppingList.add(item);
}
@Override
public int numItems() {
return shoppingList.size();
}
@Override
public LocalDate getDate() {
return createdDate;
}
@Override
public double totalPrice() {
double total = 0.0;
for(IShoppingItem item : shoppingList) {
total += item.getPrice();
}
return total;
}
@Override
public int getItemCount(String itemName) {
int count = 0;
for(IShoppingItem item : shoppingList) {
if(item.getName().equals(itemName)) {
count++;
}
}
return count;
}
@Override
public int removeExpensiveItems(double priceLimit) {
int count =0;
int index =0;
while(index<shoppingList.size()) {
IShoppingItem item = shoppingList.get(index);
if(item.getPrice()>= priceLimit) {
shoppingList.remove(index);
count++;
}
else {
index++;
}
}
return count;
}
}
package lecture14;
import static org.junit.jupiter.api.Assertions.*;
import java.time.LocalDate;
import java.util.List;
import java.util.Random;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class ShoppingListTest {
private LocalDate date;
private IShoppingList list;
private ShoppingItem milk;
private ShoppingItem bread;
@BeforeEach
void setup() {
date = LocalDate.now();
list = new ShoppingList(date);
milk = new ShoppingItem("Milk",12);
bread = new ShoppingItem("Bread", 10.2);
}
@Test
void testCanConstruct() {
LocalDate foundDate = list.getDate();
assertEquals(date, foundDate);
}
@Test
void testCanAdd() {
List<IShoppingItem> items = list.getAllItems();
assertTrue(items.isEmpty());
list.add(milk);
items = list.getAllItems();
assertTrue(items.contains(milk));
}
@Test
void testGetTotalPrice() {
assertEquals(0, list.totalPrice());
list.add(milk);
assertEquals(milk.getPrice(), list.totalPrice());
list.add(milk);
assertEquals(milk.getPrice()*2, list.totalPrice());
}
@Test
void testShoppingItem() {
assertEquals(10.2, bread.getPrice());
String name = bread.getName();
assertEquals("Bread", name);
}
@Test
void testGetItemCount() {
assertEquals(0, list.getItemCount("Milk"));
list.add(milk);
assertEquals(1, list.getItemCount("Milk"));
list.add(milk);
assertEquals(2, list.getItemCount("Milk"));
list.add(bread);
assertEquals(2, list.getItemCount("Milk"));
}
@Test
void addInvalidShoppingItem() {
ShoppingItem blank = new ShoppingItem("", 10);
assertThrows(IllegalArgumentException.class, () -> list.add(blank));
}
@Test
void removeExpensiveItems() {
fillRandom();
}
private void fillRandom() {
String[] names = {"Milk","TV","Bread","Banana","Shoes","Jacket"};
Random random = new Random();
for(int i=0; i<100; i++) {
String name = names[random.nextInt(names.length)];
ShoppingItem item = new ShoppingItem(name, random.nextDouble(1000));
list.add(item);
}
int sizeBefore = list.numItems();
double limit = 500.0;
int removed = list.removeExpensiveItems(limit);
for(IShoppingItem item : list) {
assertTrue(item.getPrice()<limit,"Price was supposed to be less than "+limit+" but was: "+item.getPrice());
}
assertEquals(sizeBefore-list.numItems(), removed,"The number of removed items does not match the change of size in the list");
}
}
......@@ -15,4 +15,18 @@ public class Book {
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;
}
}
package lecture6_interface;
public class FirePokemon implements IPokemon {
String name;
int healthPoints;
int strength;
// Constructor
public FirePokemon(String name, int strength){
this.name = name;
this.healthPoints = 100;
this.strength = strength;
}
/**
* Get name of the pokémon
* @return name of pokémon
*/
public String getName() {
return name;
}
/**
* Get strength of the pokémon
* @return strength of pokémon
*/
public int getStrength() {
return strength;
}
/**
* Get current health points of pokémon
* @return current HP of pokémon
*/
public int getCurrentHP() {
return healthPoints;
}
/**
* Check if the pokémon is alive.
* A pokemon is alive if current HP is higher than 0
* @return true if current HP > 0, false if not
*/
public boolean isAlive() {
return healthPoints>0;
}
/**
* Damage the pokémon. This method reduces the number of
* health points the pokémon has by <code>damageTaken</code>.
* If <code>damageTaken</code> is higher than the number of current
* health points then set current HP to 0.
*
* @param damageTaken
*/
public void damage(int damageTaken) {
healthPoints -= damageTaken;
if(healthPoints<0)
healthPoints = 0;
}
@Override
public void attack(IPokemon target) {
int dmg = this.getStrength()*target.getStrength();
target.damage(dmg);
}
}
package lecture6_interface;
public interface IAttack {
/**
* Performs an attack on another Pokemon
* @param target
*/
public void attack(IPokemon target);
}
package lecture6_interface;
public interface IPokemon {
/**
* Get name of the pokémon
* @return name of pokémon
*/
public String getName();
/**
* Get strength of pokémon
* @return strength of pokémon
*/
public int getStrength();
/**
* Get current number of health points of pokémon
* @return current HP of pokémon
*/
public int getCurrentHP();
/**
* Check if the pokémon is alive.
* A pokemon is alive if current HP is higher than 0
* @return true if current HP > 0, false if not
*/
public boolean isAlive();
/**
* Attack another pokémon. The method conducts an attack by <code>this</code>
* on <code>target</code>. Calculate the damage using the pokémons strength
* and a random element. Reduce <code>target</code>s health.
*
* If <code>target</code> has 0 HP then print that it was defeated.
*
* @param target pokémon that is being attacked
*/
public void attack(IPokemon target);
/**
* Damage the pokémon. This method reduces the number of
* health points the pokémon has by <code>damageTaken</code>.
* If <code>damageTaken</code> is higher than the number of current
* health points then set current HP to 0.
*
* The method should print how much HP the pokemon is left with.
*
* @param damageTaken
*/
public void damage(int damageTaken);
}
package lecture6_interface;
public class Pokemon implements IPokemon{
String name;
int healthPoints;
int strength;
IAttack attack;
// Constructor
Pokemon(String name, int strength, IAttack attack){
this.name = name;
this.healthPoints = 100;
this.strength = strength;
this.attack = attack;
}
/**
* Get name of the pokémon
* @return name of pokémon
*/
public String getName() {
return name;
}
/**
* Get strength of the pokémon
* @return strength of pokémon
*/
public int getStrength() {
return strength;
}
/**
* Get current health points of pokémon
* @return current HP of pokémon
*/
public int getCurrentHP() {
return healthPoints;
}
/**
* Check if the pokémon is alive.
* A pokemon is alive if current HP is higher than 0
* @return true if current HP > 0, false if not
*/
public boolean isAlive() {
return healthPoints>0;
}
/**
* Damage the pokémon. This method reduces the number of
* health points the pokémon has by <code>damageTaken</code>.
* If <code>damageTaken</code> is higher than the number of current
* health points then set current HP to 0.
*
* @param damageTaken
*/
public void damage(int damageTaken) {
healthPoints -= damageTaken;
if(healthPoints<0)
healthPoints = 0;
}
/**
* Attack another pokémon. The method conducts an attack by <code>this</code>
* on <code>target</code>. Calculate the damage using the pokémons strength
* and a random element. Reduce <code>target</code>s health.
*
* If <code>target</code> has 0 HP then print that it was defeated.
*
* @param target pokémon that is being attacked
*/
public void attack(IPokemon target) {
attack.attack(target);
}
@Override
public String toString() {
return name+" has "+healthPoints+" left.";
}
}
package lecture6_interface;
import java.util.Random;
public class RandomAttack implements IAttack{
Random rnd;
public RandomAttack() {
rnd = new Random();
}
@Override
public void attack(IPokemon target) {
int dmg = rnd.nextInt(10);
target.damage(dmg);
}
}
package lecture6_interface;
public class SleepAttack implements IAttack{
public SleepAttack() {
}
@Override
public void attack(IPokemon target) {
target.damage(100);
}
}