Record Sheet of Methods Coding Exercises

A record of answers of some basic coding exercise.
Still updating.

Dealing with Numbers

  • To compare the first 3 digits of two numbers

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    public class DecimalComparator{
    public static boolean areEqualByThreeDecimalPlaces(double num1, double num2){
    int int1 = (int) (num1 * 1000);
    int int2 = (int) (num2 * 1000);
    System.out.println(int1);
    System.out.println(int2);
    if (int1 == int2){
    return true;
    } else {
    return false;
    }
    }
    }
  • To printout hh mm ss with seconds or minutes input

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    public static void getDurationString (int minutes, int seconds){
    if (minutes < 0 || seconds <0 || seconds >59 ){
    System.out.println("Invalid value!");
    } else{
    int h = minutes / 60;
    String hh = h + "h ";
    if (h <10){
    hh = "0" + hh;
    }
    int m = minutes % 60;
    String mm = m + "m ";
    if (m < 10){
    mm = "0" + mm;
    }
    String ss = seconds + "s";
    if (seconds<10){
    ss = "0" + ss;
    }
    System.out.println(hh + mm + ss );
    }
    }

    public static void getDurationString (int seconds){
    if (seconds < 0)
    System.out.println("Invalid value!");
    else {
    int minutes = seconds/60;
    int second = seconds%60;
    getDurationString(minutes,second);
    }
    }
  • To return the reverse of a number (1234->4321)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    public static int reverse(int number){
    int i = 0;
    while (number != 0){
    i *= 10;
    i += number % 10;
    number /= 10;
    }
    return i;
    }
  • To print number in word (1234 -> ONE TWO THREE FOUR)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    public static void printNumberInWord(int num){
    String output;
    String[] result = {"ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE"};
    if (num < 0 || num > 9){
    output = "OTHER";
    } else {
    output = result[num];
    }
    System.out.println(output);
    }
  • To count the digits of a number (1234 -> 4)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    public static int getDigitCount(int number){
    if (number <0){
    return -1;
    }
    int i = 0;
    if (number == 0){
    i = 1;
    }
    for (number = number; number > 0; number /=10){
    i++;
    }
    return i;
    }
  • To return the largest prime factor of a number without another method

    1
    2
    3
    4
    5
    6
    7
    8
    9
    public static int getLargestPrime(int number) {
    if (number <= 1) return -1;
    for (int i = number/2; i > 1; i--) {
    if (number % i == 0) {
    number = i;
    }
    }
    return number;
    }

Dealing with Read Input

  • Use a while loop to read input and record max / min input

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    public static void minAndMaxInputChallenge(){
    Scanner input = new Scanner(System.in);
    int inputNum;
    int maxNum = Integer.MIN_VALUE;
    int minNum = Integer.MAX_VALUE; //ensure that the first input will always update the max and min
    while (true){
    System.out.println("Enter number: ");
    if (input.hasNextInt()){
    inputNum = input.nextInt();
    if (minNum > inputNum) minNum = inputNum;
    if (maxNum < inputNum) maxNum = inputNum;
    } else {
    break;
    }
    input.nextLine();
    }
    System.out.println("The Max number is " + maxNum);
    System.out.println("The Min number is " + minNum);
    input.close();
    }
  • Use a loop to read input and return the sum and ave

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    public static void inputThenPrintSumAndAverage() {
    Scanner reader = new Scanner(System.in);
    int sum = 0;
    double ave = 0;
    int counter = 0;
    while (true) {
    if (reader.hasNextInt()) {
    sum += reader.nextInt();
    counter++;
    ave = (double) sum / counter; //to avoid lose of accuracy
    } else {
    System.out.println("SUM = " + sum + " AVG = " + Math.round(ave));
    break;
    }
    }
    }

Dealing with Class

  • To return the distance between this point and another point

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    public class Point {
    private int x;
    private int y;

    public Point(int x, int y) {
    this.x = x;
    this.y = y;
    }
    public int getX() {
    return x;
    }
    public int getY() {
    return y;
    }
    public double distance(int x, int y){
    return Math.hypot((this.x-x),(this.y-y));
    }
    public double distance(Point another){
    return distance(another.getX(), another.getY());
    }
    }
  • To use polymorphism to call the correct method for an object based on its run-time type

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    public class Main {
    public static void main (String[] args){
    Car[] cars = new Car[2];
    cars[0] = new Benz("BMW",8,400);
    cars[1] = new Lancer("Audi",12,350);

    for (Car i:cars){
    i.startEngine();
    i.accelerate();
    }
    }
    }

    class Car{
    private String name;
    private int cylinders;
    private int wheels = 4;

    public Car(String name, int cylinders) {
    this.name = name;
    this.cylinders = cylinders;
    }
    public void startEngine(){
    System.out.println("Car engine ON!");
    }
    public void accelerate(){
    System.out.println("Speed UP!");
    }
    }

    class Benz extends Car{
    int maxSpeed;
    public Benz(String name, int cylinders, int maxSpeed) {
    super(name, cylinders);
    this.maxSpeed = maxSpeed;
    }

    @Override
    public void startEngine() {
    System.out.println("Benz Power ON!");
    }
    public void accelerate(){
    System.out.println("Something is acc!");
    }
    }

    class Lancer extends Car{
    int maxSpeed;
    public Lancer(String name, int cylinders, int maxSpeed) {
    super(name, cylinders);
    this.maxSpeed = maxSpeed;
    }

    @Override
    public void startEngine() {
    System.out.println("LANCER is ready!");
    }
    }

Dealing with Arrays

  • Sort array of primitive types in descending order
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    public static int[] sortIntegers(int[] array){
    //int[] newArray = array; invalid as it only copy the address
    int[] newArray = Arrays.copyOf(array, array.length);
    int temp;
    boolean loop = true;
    while(loop){
    loop = false;
    for (int i = 0; i < newArray.length -1; i++){
    if (newArray[i] < newArray[i+1]){
    temp = newArray[i];
    newArray[i] = newArray[i+1];
    newArray[i+1] = temp;
    loop = true;
    }
    }
    }
    return newArray;
    }

or can make use of Array.sort

1
2
3
4
5
6
7
8
9
public static int[] sortIntegers(int[] array){
int[] newArray = Arrays.copyOf(array, array.length);
for(int i=0;i<newArray.length;i++)
newArray[i]=-newArray[i];
Arrays.sort(newArray);
for(int i=0;i<newArray.length;i++)
newArray[i]=-newArray[i];
return newArray;
}

  • Reverse an array

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    public static void reverse(int[] array){
    int maxIndex = array.length - 1;
    int halfLength = array.length / 2;
    int temp;
    for (int i = 0; i < halfLength; i++){
    temp = array[i];
    array[i] = array[maxIndex - i];
    array[maxIndex -i] = temp;
    }
    }
  • Reverse an array (another method)

    1
    2
    3
    4
    5
    6
    7
    int[] reversedArray = new int[array.length];
    for (int i = 0; i < array.length; i++){
    reversedArray[i] = array[array.length - 1 - i];
    }
    for (int i = 0; i < array.length; i ++){
    array[i] = reversedArray[i];
    }

Dealing with ArrayList

  • Query an object in arraylist with part of the parameters
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    public class Main {
    public static MobilePhone contactList = new MobilePhone("mynumber");
    public static Scanner scanner = new Scanner (System.in);

    public static void main (String[] args){
    queryContact();
    }
    public static void queryContact(){
    System.out.println("Enter the name of contact: ");
    String name = scanner.nextLine();
    Contacts foundContact = contactList.queryContact(name);
    if (foundContact !=null){
    System.out.println("The contact is found.\n");
    } else {
    System.out.println("Error! Cannot find tha contact\n");
    }
    }
    }
    class MobilePhone {
    private String myNumber;
    private ArrayList<Contacts> myContacts;

    public MobilePhone(String myNumber) {
    this.myNumber = myNumber;
    this.myContacts = new ArrayList<>();
    }
    public Contacts queryContact (String name){
    int index = searchContact(name);
    if (index >=0){
    Contacts foundContact = myContacts.get(index);
    return foundContact;
    } else
    return null;
    }
    private int searchContact(String name){
    for (int i =0; i <myContacts.size(); i++){
    if (myContacts.get(i).getName().equals(name))
    return i;
    }
    return -1;
    }
    }
    class Contacts {
    private String name;
    private String phoneNumber;

    public Contacts(String name, String phoneNumber) {
    this.name = name;
    this.phoneNumber = phoneNumber;
    }
    public String getName() {
    return name;
    }
    }

Dealing with Interface

  • Create a Interface allows an object to be saved through List and populate tehe object’s fields from an List
    Then create class implements the interface and main methods to save and load the arraylist

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    import java.util.ArrayList;
    import java.util.List;

    public class Main {
    public static void main(String[] args) {
    Player playerOne= new Player("Marvin");
    playerOne.setLevel(16);
    playerOne.setMoney(255.32);

    saveObject(playerOne);
    loadObject(playerOne);
    }

    public static void saveObject(Saveable objectToSave){
    for (int i =0; i < objectToSave.returnList().size(); i++){
    System.out.println("Saving " +objectToSave.returnList().get(i) + "...");
    // simulate the actual save process
    }
    System.out.println("Save Done!");
    }

    public static void loadObject(Saveable objectToLoad){
    // simulate the actual save file to be loaded
    List<String> values = new ArrayList<>();
    values.add(0,"Dandin");
    values.add(1,"35");
    values.add(2,"65535");

    objectToLoad.populateFields(values);
    System.out.println("Load Done!");
    }
    }

    interface Saveable {
    List returnList ();
    void populateFields (List<String> arraylist);
    }

    class Player implements Saveable{
    private String name;
    private int level = 1;
    private double money = 0;

    public Player(String name) {
    this.name = name;
    }

    public String getName() {
    return name;
    }

    public void setLevel(int level) {
    this.level = level;
    }

    public void setMoney(double money) {
    this.money = money;
    }

    @Override
    public List returnList() {
    List<String> newList = new ArrayList<>();
    newList.add(0, this.name);
    newList.add(1, Integer.toString(this.level));
    newList.add(2, Double.toString(this.money));
    return newList;
    }

    @Override
    public void populateFields(List<String> arraylist) {
    if (arraylist.size() > 0 ){
    this.name = arraylist.get(0);
    this.level = Integer.parseInt(arraylist.get(1));
    this.money = Double.parseDouble(arraylist.get(2));
    }
    }

    @Override
    public String toString() {
    return "Player{" +
    "name='" + name + '\'' +
    ", level='" + level + '\'' +
    ", money='" + money + '\'' +
    '}';
    }
    }
  • Create a button with ClickListener

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    public class Main {
    private static Button btnPrint = new Button("Print");
    public static void main(String[] args) {
    class ClickListener implements Button.OnClickListener{
    public ClickListener(){
    System.out.println("I've been attached");
    } //constructor

    @Override
    public void OnClick(String title){
    System.out.println(title + " was clicked");
    }
    }

    btnPrint.setOnClickListener(new ClickListener()); //clickListener was added to a no name object
    btnPrint.onClick(); // call the Button class methods
    }
    }
    class Button {
    private String title;
    private OnClickListener onClickListener; //using the filed to call the method itself

    public Button(String title) {
    this.title = title;
    }

    public void setOnClickListener(OnClickListener onClickListener) {
    this.onClickListener = onClickListener;
    }

    public void onClick(){ // this is the method to be called as Button class
    this.onClickListener.OnClick(this.title); //call the interface function, name doesn't matter
    }

    public interface OnClickListener { //use as a Class
    void OnClick(String title);
    }
    }

Dealing with Binary Search Tree

Based on a ListItem class with root object and left and right ListItems in the fields

  • Traverse the BST list, using recursive method

    1
    2
    3
    4
    5
    6
    7
    public void traverse(ListItem root) {
    if (root != null){
    traverse(root.left());
    System.out.println(root.getValue());
    traverse(root.right());
    }
    }
  • Remove an item in the BST list

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    public boolean removeItem(ListItem item) {
    if (getRoot() == null){
    System.out.println("Error, empty list");
    return false;
    }
    ListItem currentItem = getRoot();
    ListItem parentItem = currentItem;
    int compare;
    while (currentItem != null){
    compare = currentItem.compareTo(item);
    if (compare < 0){
    parentItem = currentItem;
    currentItem = currentItem.right();
    } else if (compare >0){
    parentItem = currentItem;
    currentItem = currentItem.left();
    } else {
    performRemoval (currentItem, parentItem);
    return true;
    }
    }
    return false;
    }

    private void performRemoval (ListItem item, ListItem parent){
    if (item.right() == null){
    if (parent.right() == item){
    parent.setRight(item.left());
    } else if (parent.left() == item){
    parent.setLeft(item.left());
    } else { //parent = item, item is the root
    this.root = item.left();
    }
    } else if (item.left() == null){
    if (parent.right() == item){
    parent.setRight(item.right());
    } else if (parent.left() == item){
    parent.setLeft(item.right());
    } else {
    this.root = item.right();
    }
    } else {
    ListItem current = item.right();
    ListItem leftmostParent = item;
    while (current.left() != null){
    leftmostParent = current;
    current = current.left();
    }
    item.setValue(current.getValue());
    if (leftmostParent == item){
    item.setRight(current.right());
    } else {
    leftmostParent.setLeft(current.right());
    }
    }
    }