- Assignment 1
- Assignment 2
- Assignment 3
- Assignment 4
- Assignment 5
- Assignment 6
- Assignment 7
- Assignment 8
- Assignment 9
- Assignment 10
- Assignment 11
- 1 - Hello, World!
- 3.12.1 - Ligningskontoret, program som leser inn fødselsdagen og skriver ut kontornummeret
- 3.12.2 - Program som leser inn heltall og finner ut om tall positivt, delelig eller lukket intervall
- 4.14.2 - Program som tegner figur i kommandovinduet
- 4.14.3 - Program som skriver ut tallverdiene for et intervall av tegn
- 4.14.4 - Program som regner ut en hovedkarakter ut fra en rekke karakterer
- 4.14.6 - Program som omformer mellom 10-tallsystemet og et hvilket som helst annet tallsystem
- 5.9.1 - Program som lar bruker oppdatere prosjektinformasjon
- 6.10.1 - Avlønning av sensorer ved eksamen
- 7.8.2 - Klasse som holder orden på fraværet til elevene i en skoleklasse
- 8.16.2 - Klassen NyString med objekt av klassen StringBuilder
- 9.11.1 - Klasse som inneholder en tabell med priser pĂĄ varer
- 9.11.3 - Klassen Matrise
- 10.9.2 - Applikasjon som tegner rektangel
- 10.9.3 - Applikasjonen Flekker med linjer
- 10.9.4 - Program som tegner polygon
- 10.9.5 - Program som tegner tre ulike geometriske figurer i tilfeldige farger spredt rundt i et vindu
- 11.10.2 - Program som lager en plakat som inneholder linjer med tekst
- 11.10.3 - Klasse for å håndtere bøker
- 11.10.4 - Klassen Dato
- 12.10.2 - Klassen Transaksjon og Konto
Binary Search
public static int binarySearch(int[] sortedArray, int value) {
int start = 0;
int end = sortedArray.length - 1;
while (start <= end) {
int middle = (start + end) / 2;
if (sortedArray[middle] == value) {
return middle;
} else {
if (sortedArray[middle] < value) {
start = middle + 1;
} else {
end = middle - 1;
}
}
}
return -start - 1; // returns negative int if value not found.
}
toString-method
@Override
public String toString() {
return "Name: " + firstName + " " + lastName;
}
equals-method
@Override
public boolean equals(Object other) {
// type check
if (!(other instanceof ClassName)) return false;
// self check
if (this == other) return true;
// cast
ClassName className = (ClassName) other;
// field comparison
return Objects.equals(variableName, className.variableName)
}
compareTo-method
import java.util.Arrays;
public class Person implements Comparable<Person> {
private String firstName;
private String lastName;
private int dateOfBirth; // Date format: yyyyMMdd
public Person(String firstName, String lastName, int dateOfBirth) {
this.firstName = firstName;
this.lastName = lastName;
this.dateOfBirth = dateOfBirth;
}
@Override
public int compareTo(Person other) {
if (other == null) {
throw new NullPointerException();
}
if (dateOfBirth < other.dateOfBirth) {
return -1;
}
if (dateOfBirth > other.dateOfBirth) {
return 1;
}
return 0;
}
@Override
public String toString() {
return firstName + " " + lastName + " " + dateOfBirth;
}
public static void main(String[] args) {
Person[] persons = new Person[5];
persons[0] = new Person("James", "Bond", 19201111);
persons[1] = new Person("Jennifer", "Aniston", 19690211);
persons[2] = new Person("Tom", "Hardy", 19770915);
persons[3] = new Person("Brad", "Pitt", 19631218);
persons[4] = new Person("Johnny", "Cash", 19320226);
for (Person p : persons) {
System.out.println(p);
}
Arrays.sort(persons);
for (Person p : persons) {
System.out.println(p);
}
}
}
// James Bond 19201111
// Jennifer Aniston 19690211
// Tom Hardy 19770915
// Brad Pitt 19631218
// Johnny Cash 19320226
//
// James Bond 19201111
// Johnny Cash 19320226
// Brad Pitt 19631218
// Jennifer Aniston 19690211
// Tom Hardy 19770915
compare-method
// PersonComparatorFirstName should be declared in a own file named PersonComparatorFirstName.java
import java.util.Comparator;
public class PersonComparatorFirstName implements Comparator<Person> {
@Override
public int compare(Person person1, Person person2) {
if (person1 == null && person2 == null) return 0;
if (person1 == null) return -1;
if (person2 == null) return 1;
if (person1.equals(person2)) return 0;
return person1.getFirstName().compareTo(person2.getFirstName());
}
}
// PersonComparatorLastName should be declared in a own file named PersonComparatorLastName.java
import java.util.Comparator;
public class PersonComparatorLastName implements Comparator<Person> {
@Override
public int compare(Person person1, Person person2) {
if (person1 == null && person2 == null) return 0;
if (person1 == null) return -1;
if (person2 == null) return 1;
if (person1.equals(person2)) return 0;
return person1.getLastName().compareTo(person2.getLastName());
}
}
// Person should be declared in a own file named Person.java
import java.util.Arrays;
public class Person implements Comparable<Person> {
private String firstName;
private String lastName;
private int dateOfBirth; // Date format: yyyyMMdd
public Person(String firstName, String lastName, int dateOfBirth) {
this.firstName = firstName;
this.lastName = lastName;
this.dateOfBirth = dateOfBirth;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getDateOfBirth() {
return dateOfBirth;
}
@Override
public int compareTo(Person other) {
if (other == null) {
throw new NullPointerException();
}
if (dateOfBirth < other.dateOfBirth) {
return -1;
}
if (dateOfBirth > other.dateOfBirth) {
return 1;
}
return 0;
}
@Override
public String toString() {
return firstName + " " + lastName + " " + dateOfBirth;
}
public static void main(String[] args) {
Person[] persons = new Person[5];
persons[0] = new Person("James", "Bond", 19201111);
persons[1] = new Person("Jennifer", "Aniston", 19690211);
persons[2] = new Person("Tom", "Hardy", 19770915);
persons[3] = new Person("Brad", "Pitt", 19631218);
persons[4] = new Person("Johnny", "Cash", 19320226);
System.out.println("Unsorted:");
for (Person p : persons) {
System.out.println(p);
}
Arrays.sort(persons);
System.out.println("\nSorted by date of birth:");
for (Person p : persons) {
System.out.println(p);
}
Arrays.sort(persons, new PersonComparatorFirstName());
System.out.println("\nSorted by first name:");
for (Person p : persons) {
System.out.println(p);
}
Arrays.sort(persons, new PersonComparatorLastName());
System.out.println("\nSorted by last name:");
for (Person p : persons) {
System.out.println(p);
}
}
}
// Unsorted:
// James Bond 19201111
// Jennifer Aniston 19690211
// Tom Hardy 19770915
// Brad Pitt 19631218
// Johnny Cash 19320226
//
// Sorted by date of birth:
// James Bond 19201111
// Johnny Cash 19320226
// Brad Pitt 19631218
// Jennifer Aniston 19690211
// Tom Hardy 19770915
//
// Sorted by first name:
// Brad Pitt 19631218
// James Bond 19201111
// Jennifer Aniston 19690211
// Johnny Cash 19320226
// Tom Hardy 19770915
//
// Sorted by last name:
// Jennifer Aniston 19690211
// James Bond 19201111
// Johnny Cash 19320226
// Tom Hardy 19770915
// Brad Pitt 19631218
Read text from file
import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
try {
// An abstract representation of file and directory pathnames.
File file = new File("fileName.txt");
// FileReader is meant for reading streams of characters.
FileReader fr = new FileReader(file);
// BufferedReader reads text from a character-input stream.
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
while (line != null) {
System.out.println(line);
line = br.readLine();
}
// br.close and fr.close closes the stream and releases any system resources associated with it.
br.close();
fr.close();
} catch (FileNotFoundException e) {
System.out.println("File not found!");
} catch (IOException e) {
System.out.println("I/O exception of some sort has occurred!");
}
Write text to file
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.PrintWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
try {
// An abstract representation of file and directory pathnames.
File file = new File("fileName.txt");
// boolean indicating whether or not to append the data written.
boolean append = true;
// FileWriter is meant for writing character files.
FileWriter fw = new FileWriter(file, append);
// BufferedWriter writes text to a character-output stream.
BufferedWriter bw = new BufferedWriter(fw);
// PrintWriter prints formatted representations of objects to a text-output stream.
PrintWriter pw = new PrintWriter(bw);
// PrintWriter offers the same methods as System.out
pw.println("Some formatted text,\nwe want to write to a file.");
// bw.close, pw.close and fw.close closes the stream and releases any system resources associated with it.
bw.close();
pw.close();
fw.close();
} catch (FileNotFoundException e) {
System.out.println("File not found!");
} catch (IOException e) {
System.out.println("I/O exception of some sort has occurred!");
}
Write object to file
import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
// Remember to use implements Serializable behind the class name for the classes you want to write.
try {
// An abstract representation of file and directory pathnames.
File file = new File("fileName.ser");
// FileOutputStream is an output stream for writing data to a File or to a FileDescriptor.
FileOutputStream fos = new FileOutputStream(file);
// An ObjectOutputStream writes primitive data types and graphs of Java objects to an OutputStream.
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(theObject);
// oos.close and fos.close closes the stream and releases any system resources associated with it.
oos.close();
fos.close();
} catch (FileNotFoundException e) {
System.out.println("File not found!");
} catch (IOException e) {
System.out.println("I/O exception of some sort has occurred!");
}
Read object from file
import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
try {
// An abstract representation of file and directory pathnames.
File file = new File("fileName.ser");
// FileInputStream is meant for reading streams of raw bytes
FileInputStream fis = new FileInputStream(file);
// ObjectInputStream deserializes objects previously written using an ObjectOutputStream.
ObjectInputStream ois = new ObjectInputStream(fis);
TheClass theClass = (TheClass) ois.readObject();
// ois.close and fis.close closes the stream and releases any system resources associated with it.
ois.close();
fis.close();
} catch (FileNotFoundException e) {
System.out.println("File not found!");
} catch (IOException e) {
System.out.println("I/O exception of some sort has occurred!");
} catch (ClassNotFoundException e) {
System.out.println("Class not found exception has occurred!");
}