Friday, 20 February 2015

Using a Stack in Java

Someone asked me to help him with a basic code of using a stack and here it is: Just creating a stack and adding 3 string objects to it using push then playing around with the methods iimplemented in a stack object.


public class StackExample {
   
    public static void main(String[] args) {
       
        Stack st = new Stack();
        st.push("Onty");
        st.push("Bagwasi");
        st.push("Programming");
       
        //prints the first element in the stack - Onty
        System.out.println(st.firstElement());
       
        //prints the element at index 0 - Onty
        System.out.println(st.get(0));
       
        //prints the index of Bagwasi - 1
        System.out.println(st.indexOf("Bagwasi"));
       
        //prints the last element in the stack
        System.out.println(st.lastElement());
       
        //this just checks what the last element is and prints it
        System.out.println(st.peek());
       
        //pop gets the last item in the stack and removes it from the stack
        st.pop();
       
        //now if u peek, the last item on the stack has changed
        System.out.println(st.peek());
    }
   
}

Simple Maths Arithmetic using a switch statement

Now the following question was given to my students as a lab exercise.
The program should take 2 integers and an operand from the user and perform a maths arithmetic based on the operand supplied to the method by the user and here is the solution:


public class MathsSwich {

    public static void main(String[] args) {
        //testing the program
        compute(8, 3, "%");
    }

    public static void compute(int x, int y, String st) {

        switch (st) {
            case "+":
                System.out.println(x + " + " + y + " = " + (x + y));
                break;
            case "-":
                System.out.println(x + " - " + y + " = " + (x - y));
                break;
            case "/":
                System.out.println(x + " / " + y + " = " + (x / y));
                break;
            case "*":
                System.out.println(x + " * " + y + " = " + (x * y));
                break;
            case "%":
                System.out.println(x + " % " + y + " = " + (x % y));
                break;
            default:
                System.out.println("Please check operand!");

        }

    }

}

This is pretty straight forward as it is an alternative to the program i wrote using the if-else statements. Read it and understand it then testing using different scenarios. Happy Coding everyone!

Java program to create a zip file

So I was bored last night and thought I should write a code that creates a file and puts it into a zip file. So its very simple and here is the code in Java:

import java.io.*;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class WriteZip {

    public static void main(String[] args) throws IOException {

        FileOutputStream fout = new FileOutputStream("file.zip");
        ZipOutputStream zout = new ZipOutputStream(fout);
        ZipEntry ze = new ZipEntry("test.doc");
        zout.putNextEntry(ze);
        zout.closeEntry();
        zout.close();

    }

}

  • So what happens here is that we create a FileOutputStream object which i called fout. This is the object that will create our file.zip
  • The next step is to create a ZipOutputStream which is an object that takes our FileOutputStream object called fout.
  • Now we create a zip entry which is a new file called test.doc 
  • We then put this zip entry into our zipoutput stream,
  • Lastly we close our zout
Happy coding everyone! Lookout for more cool java codes

Monday, 16 February 2015

Print the first n prime numbers in Java

So I know my students are having a tough time with this one. All I asked them to do was to :

-create a method that checks if a number is prime
-modify the program to print the first n prime numbers

Of course it is a bit tricky but easy to do so here is my code and i will explain it in a bit:


public class PrimeNumber {

    public static void main(String[] args) {
        int count = 0, n = 15;
        boolean flag = true;

        for (int j = 2; flag == true; j++) {
            if ((isPrime(j)) && (count < n)) {
                System.out.print(j + " ");
                count++;
            }

            if (count == n) {
                flag = false;
            }
           // System.out.println(flag);

        }
    }

    public static boolean isPrime(int n) {

        for (int i = 2; i < n; i++) {

            if (n % i == 0) {
                return false;
            }

        }
        return true;
    }
}



So basically all that happens here is that a prime number only has two factors. The method isPrime takes a parameter n which will be checked whether its prime or not. So I decided to start at i=2 because 2 is the first prime number. 

  if (n % i == 0) {
                return false;
            }
 

This if statement will check if there are any other factors that can divide the number n, if the factors exist then n is not prime. Study it and run it and see if you can make something out of it. Happy coding 

Thursday, 12 February 2015

Simple Math calculator in Java

So I gave my students a task the following question:





Write a java function that take three parameters, the first two are integers and the last one is a string. The value of the last parameter will always be an operator (e.g. “+”, “-“, “%” etc. Your program should check the value of the operator and perform such action on the two integers. For example, if the integer parameters are 5 and 10, and the operator parameter is “+”, then your program will add the two integers together and print the results to the screen.



  •  Use the If-else control structure
  • Use the Switch control structure 


This was just a very simple program to get a salary and subtract the medical aid contribution, income tax and pension fund. This is my solution here and i will explain how it works.

 
public class Maths {

    public static void main(String[] args) {
        compute(5, 2, "-");
    }

    public static void compute(int x, int y, String st) {

        String str = st;
        char c = str.charAt(0);

        if (c == '+') {
            System.out.println(x + " + " + y + " = " + (x + y));
        } else if (c == '-') {
            System.out.println(x + " - " + y + " = " + (x - y));
        } else if (c == '/') {
            System.out.println(x + " / " + y + " = " + (x / y));
        } else if (c == '*') {
            System.out.println(x + " * " + y + " = " + (x * y));
        } else if (c == '%') {
            System.out.println(x + " % " + y + " = " + (x % y));
        } else {
            System.out.println("Please Check Operand!");
        }

    }

}







Explanation of the code



There is a method called compute which takes 3 parameters, int x is an integer and int y is also an integer. Tha last parameter is the symbol which represents the operand to be used on both x and y, for example, if the parameters are 10,2,"*" then the arithmetic performed will be 10 multiplied by 2 and will print out the answer to the screen. 

The if else statements are just responsible for checking the kind of operation to perform by checking whether the operator is a legal one. if you parse anything not recognisable the error message is printed to the screen.

The above code can also be done using the switch statements as shown below.


public class MathsSwich {

    public static void main(String[] args) {
        compute(8, 3, "%");
    }

    public static void compute(int x, int y, String st) {

        String str = st;
        char c = str.charAt(0);

        switch (c) {
            case '+':
                System.out.println(x + " + " + y + " = " + (x + y));
                break;
            case '-':
                System.out.println(x + " - " + y + " = " + (x - y));
                break;
            case '/':
                System.out.println(x + " / " + y + " = " + (x / y));
                break;
            case '*':
                System.out.println(x + " * " + y + " = " + (x * y));
                break;
            case '%':
                System.out.println(x + " % " + y + " = " + (x % y));
                break;
            default:
                System.out.println("Please check operand!");

        }

    }

}


The output of the above programs will always be the same. Cheers and see you next time on another simple and fun java code