Skip to content

janmarius/TDAT1001-Introduction-to-Programming

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

27 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

TDAT1001 - Introduction to Programming

Assignments

Additional Excercises

Code Examples

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!");
}

About

Course during B.Sc in Computer Engineering

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published