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());
}
}
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.
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:
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!
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
Labels:
Creating a zip file in java,
Java Compress files,
Java Zip Folder
Posted by
Onty Bagwasi
at
01:44
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
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
-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
Labels:
arithmetic in java,
if else java,
java calculator,
java switch example,
switch case java
Posted by
Onty Bagwasi
at
02:24
So I gave my students a task the following question:
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
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
Thursday, 15 January 2015
Java Strings - find the location of a character in a string
Labels:
find characters in a string,
java,
java charAt,
java strings,
string operations java,
strings
Posted by
Onty Bagwasi
at
04:07
Java is a very powerful tool especially when dealing with Strings. Today we will look at a very simple program related to strings in Java. Lets say we want to write a program which store a string in a variable and print it.
public class StringExample{
public static void main(String[] args){
String st = "John Doe";
System.out.println(st);
}
}
The above program will create a variable called st and the value of the variable is John Doe. So the println statement will output John Doe because it is the value contained in st.
There are a number of items we can perform on a string object that we can also output, for example:
-count the alphabets
-check the letter at a particular location
-check for only upper case letters
-check for only lower case letters etc
so for example , let us modify the program so that we check the letter at position 2. the alphabets are numbered beginning with index 0, so at index 0 we have J, index 1 we have o, index 2 we have h..and so on...so we are expecting our program to output 'h'as our result so this is what we do:
public class StringExample{
public static void main(String[] args){
String st = "John Doe";
System.out.println(st.charAt(2));
}
}
the method called charAt(int index) is used to find the character at a location specified in the parameter location. This will return a character and since we have called it in the println statement, the character will be output to the console.
Copy this code and try to find the location of different characters and different indexes. You can also change the string itself and iterate though the string to find the location of different characters.
That is all for now next time we continue with more string manipulations
public class StringExample{
public static void main(String[] args){
String st = "John Doe";
System.out.println(st);
}
}
The above program will create a variable called st and the value of the variable is John Doe. So the println statement will output John Doe because it is the value contained in st.
There are a number of items we can perform on a string object that we can also output, for example:
-count the alphabets
-check the letter at a particular location
-check for only upper case letters
-check for only lower case letters etc
so for example , let us modify the program so that we check the letter at position 2. the alphabets are numbered beginning with index 0, so at index 0 we have J, index 1 we have o, index 2 we have h..and so on...so we are expecting our program to output 'h'as our result so this is what we do:
public class StringExample{
public static void main(String[] args){
String st = "John Doe";
System.out.println(st.charAt(2));
}
}
the method called charAt(int index) is used to find the character at a location specified in the parameter location. This will return a character and since we have called it in the println statement, the character will be output to the console.
Copy this code and try to find the location of different characters and different indexes. You can also change the string itself and iterate though the string to find the location of different characters.
That is all for now next time we continue with more string manipulations
Friday, 1 March 2013
Declaration of java variables
This is what you have to know about doing a little bit of simple mathematics using the java programming language.
Say we want to write a program that adds up two numbers,5 and 3. There are two approaches to this problem, we can either declare two variables and add the two variables together to get the answer or we can just add the two numbers up at the print statement. lets have a look at how we would do this:
public class Addition{
public static void main(String[] args){
System.out.println(5 + 3); }
}
the above solution just adds up the two numbers and prints the result. The calculation is done within the print statement. Now say we want to be able to use 5 and 3 again, maybe for another operation..the following way would be the better way of approaching this problem.
public class Addition{
public static void main(String[] args){
int x = 5;
int y = 3;
System.out.println(x+y);
}
}
the above solution works much better because if we want to reuse the variables again we will just have to add a println statement that reads:
System.out.println(x-y);
we dont have to write 5-3 agin. so basically thats how you add two integers.
IMPORTANT INFORMATION
declaring integers:
public class Addition{
public static void main(String[] args){
System.out.println(5 + 3); }
}
the above solution just adds up the two numbers and prints the result. The calculation is done within the print statement. Now say we want to be able to use 5 and 3 again, maybe for another operation..the following way would be the better way of approaching this problem.
public class Addition{
public static void main(String[] args){
int x = 5;
int y = 3;
System.out.println(x+y);
}
}
the above solution works much better because if we want to reuse the variables again we will just have to add a println statement that reads:
System.out.println(x-y);
we dont have to write 5-3 agin. so basically thats how you add two integers.
IMPORTANT INFORMATION
declaring integers:
- int x= 5; this means an integer value of 5 is stored in a variable called x, integers are numbers with no decimal places.
- double x = 5.2; this means a number with a decimal place, eg, 5.2 is stored in a value called x. next java session we will be doing strings.
Friday, 1 June 2012
The first Java Program
The first Java Program
A basic java program consists of a class name, and a main method. The following program is simple the first program for any language, the Hello World program. It consists of a class name called "HelloWorld" and a main method :
"public static void main(String[] args)"
This is the method that gets executed when the program is run, details will follow later. What the program does is that it simply prints the word "Hello World!" to the console.
The statement for printing this line is :
System.out.println("Hello World!");
So what ever you put in the brackets will be printed to the console. This is the java program here :
public class HelloWorld
{
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
The program must be saved as ClassName.java , this is important, otherwise the code will not compile.
Now to see if u are familiar with it, play around with the text in the brackets, keep changing it and keep compiling and running the code to see the results, we will move on to the next step on the next post.
PS:
*All java classes must begin with an upper case letter
*The filename of your code must match the classname, eg, if u have public class HelloWorld , you must save the file as HelloWorld.java
*If the classname consists of two words like Hello World, each word must begin with an upper case letter
like this HelloWorld
*there should be no spaces between the words making a class name
Compiling :
linux - javac HelloWorld.java
- java HelloWorld
IntelliJ - ctrl + shift + F10 = make: it will compile and run the code
- ctrl _ shift + F9 will just compile..
goodluck!
For more info, like our facebook page at https://www.facebook.com/ssutradhar35 and join our group at https://www.facebook.com/groups/computerkorner/
Monday, 14 May 2012
Developing Java applications
Hello
My name is Onty Bagwasi and I thought i should start this blog about java programming. I will do my best to cover most aspects of this language and write about them, the first post will be about the SDKs, the development environments you can use to develop java applications.
Linux:
gedit- is quite a good editor that can be used to write java applications
geany - this is another editor that i used for sometime to develop java applications
Windows
IntelliJ - according to me , this is the best java editor i have ever used. It is worth a try. available free here
Eclipse - this is the second best IDE in my opinion, feel free to choose any of these softwares. eclipse can be downloaded here!!
Dr Java - I started with this one, also free here. great development kit to have
notepad ++ - for those who love writing code, this is a good one to use
There may be more i havent covered like nedbeans , feel free to explore. Just remember to install JDK , which is the java compiler from sun microsystems site.
Next lesson we are writing our first java program. cheers
Subscribe to:
Comments (Atom)
