BSCS 208 AOOP Lab Programming Examples
BSCS 208 AOOP Lab Programming Examples
1: Hello world
a) Problem:
To develop an application that prints the message “Hello World!!!”
b) Algorithm:
Print the message “Hello World!!!”
c) Implementation:
Exercise
a) Generate an algorithm for the program
2. Distance Converter
a) Problem:
To develop an application that converts distance from meters to kilometers
b) Algorithm:
1. Import the Scanner.
2. Declare the class as public
3. Add the void main function
4. Add system.out.println() function with the message to enter length.
5. Declare input as Scanner.
6. Take the length and save it in variable.
7. Convert length and save it in other variable.
8. Add system.out.println() function to print the converted length. */
c) Implementation:
import java.util.Scanner;
/*
ALGORITHM
Exercise
a) Modify the program so that it converts from meter to centimetre
b) Modify the program so that it converts from miles to kilometres.
a) Problem:
To develop a calculator that computes the sum of two numbers
The calculator allows user to enter two numbers, then choose one of the 4 basic math operations, then
compute and display the result.
b) Algorithm:
Exercise: Study the program then generate an algorithm for it here in this section.
c) Implementation:
import java.util.Scanner;
do
{
System.out.print("1. Addition\n");
System.out.print("2. Subtraction\n");
System.out.print("3. Multiplication\n");
2
System.out.print("4. Division\n");
System.out.print("5. Exit\n\n");
System.out.print("Enter Your Choice : ");
choice = scan.next().charAt(0);
switch(choice)
{
case '1' : System.out.print("Enter Two Numbers : ");
a = scan.nextFloat();
b = scan.nextFloat();
res = a + b;
System.out.print("Result = " + res);
break;
case '2' : System.out.print("Enter Two Number : ");
a = scan.nextFloat();
b = scan.nextFloat();
res = a - b;
System.out.print("Result = " + res);
break;
case '3' : System.out.print("Enter Two Number : ");
a = scan.nextFloat();
b = scan.nextFloat();
res = a * b;
System.out.print("Result = " + res);
break;
case '4' : System.out.print("Enter Two Number : ");
a = scan.nextFloat();
b = scan.nextFloat();
res = a / b;
System.out.print("Result = " + res);
break;
case '5' : System.exit(0);
break;
default : System.out.print("Wrong Choice!!!");
break;
}
System.out.print("\n---------------------------------------\n");
}
while(choice != 5);
}
}
a) Problem:
To develop a GUI-based calculator that computes the sum of two numbers
The calculator allows user to enter two numbers, then choose one of the 4 basic math operations, then
compute and display the result.
b) Algorithm:
Exercise: Study the user interface (UI) and the code, then generate an algorithm for the three buttons.
3
c) Implementation:
2. Set properties
a. Click twice (not double click) each control to change its text property, or right-click it
then change its properties as desired.
3. Write the code
a. Right-click a component (e.g. the calculate button) and then from the pop-up menu
select:
i. Events -> Action -> actionPerformed
b. Enter code
4. Run to test the program.
NB:
The first time you run, the will be asked to select your class as the main class since you had
not created a main method initially. Select OK. Your output should be similar to this.
4
Code for calculate button
// First we define float variables.
float num1, num2, result;
try
{
if (!(jRadioButton1.isSelected()) && !(jRadioButton2.isSelected())
&&!(jRadioButton3.isSelected()) &&!(jRadioButton4.isSelected()))
{
}
if (jRadioButton1.isSelected())
{
num1 = Float.parseFloat(jTextField1.getText());
num2 = Float.parseFloat(jTextField2.getText());
5
jTextField3.setText(String.valueOf(result));
}
if (jRadioButton3.isSelected())
{
num1 = Float.parseFloat(jTextField1.getText());
num2 = Float.parseFloat(jTextField2.getText());
5. Multiplication Table
a) Problem:
To develop a program that generates a multiplication table of 9 rows and 9 columns.
b) Algorithm:
Exercise: Study the code, then generate an equivalent algorithm.
6
c) Implementation:
class MultiplicationTable
{
public static void main(String[] args)
{
for(int j=1 ; j <= 9 ; j++)
{
for(int k=1 ; k <= 9 ; k++)
{
System.out.printf("%4d", (j*k));
}
System.out.println();
}
}
}
6. Factorial Program
a) Problem:
To develop a program that generates a factorial of 7.
b) Algorithm:
Exercise: Study the code, then generate an equivalent algorithm.
c) Implementation:
Exercise
Modify the code so that the program receives the user desired number before computing the factorial.
a) Problem:
To develop a program that reverses a number then outputs the original and the newly reversed
number.
7
b) Algorithm:
Exercise: Study the code, then generate an equivalent algorithm.
c) Implementation:
public class ReverseNumber
{
public static void main(String[] args)
{
//original number
int number = 123456789;
System.out.println("Original Number is: " + number);
int reversedNumber = 0;
int temp = 0;
while(number > 0)
{
//use modulus operator to strip off the last digit
temp = number%10;
//create the reversed number
reversedNumber = reversedNumber * 10 + temp;
number = number/10;
}
8. Spliting Tokens
a) Problem:
To develop a program that splits string into tokens using empty space as a delimiter, then lists the
token stream
b) Algorithm:
Exercise: Study the code, then generate an equivalent algorithm.
c) Implementation:
public class SimpleSplitTokens
{
public static void main(String args[])
{
String s1="java string split method by javatpoint";
String[] words=s1.split("\\s");//splits the string based on whitespace
//using java foreach loop to print elements of string array
for(String w:words)
{
System.out.println(w);
}
}
}
8
9. Counting Tokens with the StringTokenizer class
a) Problem:
To develop a program that splits string into tokens using using StringTokenizer class instead of the
split() method, then counts the number of tokens in the string.
b) Algorithm:
Exercise: Study the code, then generate an equivalent algorithm.
c) Implementation
// counting tokens
System.out.println("Total tokens : " + st.countTokens());
}
}
a) Problem:
To develop a program that splits string into tokens using ‘@’ as the delimiter, then lists the tokens.
b) Algorithm:
Exercise: Study the code, then generate an equivalent algorithm.
c) Implementation
9
11. Telling the type of a character
a) Problem:
To develop a program that can tell whether a character is a letter, number, or special character.
b) Algorithm:
Exercise: Study the code, then generate an equivalent algorithm.
c) Implementation
a) Problem:
To develop a program that converts temperature from farenheit to celcius.
b) Algorithm:
Exercise: Study the code, then generate an equivalent algorithm.
10
c) Implementation
class TemperatureConverter
{
public static void main(String arg[])
{
double fahrenheit = 98.4;
}
}
Exercise
1. Use the parser method to allow the user to input the temperature of choice
2. Convert the program into a Java UI application.
a) Problem:
To develop a program that takes input of unsorted cities and then sorts them in alphabetical order.
b) Algorithm:
Exercise: Study the code, then generate an equivalent algorithm.
c) Implementation
public class CitiesOrdering
{
static String city[ ] = {"Nairobi", "Mombasa", "Nakuru", "Kisumu"};
public static void main(String[] args)
{
int size = city.length;
String temp = null;
11
}
}
for (int i=0; i<size; i++)
{
System.out.println(city[i]);
}
}
}
a) Problem:
To develop a program that takes input of a set of code expressions then deletes those that are
repeated and therefore adding no value. It can be used as a tool to improve code by reducing common
programmer errors.
b) Algorithm:
Exercise: Study the code, then generate an equivalent algorithm.
c) Implementation
//Program to Implement Common SubExpression Elimination in Java
import java.io.*;
import java.util.*;
class CommonSubExpressionEliminator
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(new
FileInputStream("d:CommonSubExpressionsInput.txt"))); // Read Input file
PrintWriter pw=new PrintWriter(new FileOutputStream(new
File("d:CommonSubExpressionsOutput.txt")),true); // Prepare Output file
String s;
Boolean flag=false;
while((s=br.readLine())!=null)
{
flag=false;
String r=s.substring(s.indexOf("=")+1); //Evaluate Right-Hand Side of Expression
12
}
if(!flag)
{
L.addElement(r); // If Expression not present in Vector, Add it inside Vector and
Print it to output file
pw.println(s);
}
}
}
}
/*
Sample Input (input.txt)
t1 = -c
t2 = a + b
t3 = d + 5
t4 = a + b
t5 = -c
==================================================
Sample Output (output.txt)
t1 = -c
t2 = a + b
t3 = d + 5
*/
a) Problem:
To develop a program that takes input of a string then counts only the unique characters.
b) Algorithm:
Exercise: Study the code, then generate an equivalent algorithm.
c) Implementation
public class CountUniqueCharactersInString
{
public static void main(String args[])
{
String str = "abcdefaaabbbcccdddeeefffkkkxxyyzz";
String temp = "";
13
temp = temp + str.charAt(i);
}
}
System.out.println(temp);
System.out.println("Unique character count: " + temp.length());
}
}
a) Problem:
To develop a program that takes input of a string, tokenizes it, then counts only the unique tokens from
the token stream.
b) Algorithm:
Exercise: Study the code, then generate an equivalent algorithm.
c) Implementation
14
boolean unique = findUpTo(lastWord, inputPhrase, wordStart);
if(unique)
{
uniqueWordCount++;
}
increment = false;
wordStart = -1;
}
}
if(increment)
{
phraseWordCount++; //in the case the last word is a valid character
final String lastWord = inputPhrase.substring(wordStart, inputPhrase.length());
boolean unique = findUpTo(lastWord, inputPhrase, wordStart);
if(unique)
{
uniqueWordCount++;
}
}
System.out.println("Words: "+phraseWordCount);
System.out.println("Unique: "+uniqueWordCount);
}
private static boolean findUpTo(String needle, String haystack, int lastPos)
{
boolean previousValid = false;
boolean unique = true;
for(int j = 0; unique && j < lastPos - needle.length(); j++)
{
final boolean nextValid = validChar(haystack.charAt(j));
if(!previousValid && nextValid)
{
// Word start
previousValid = true;
for (int k = 0; k < lastPos - j; k++)
{
if(k == needle.length())
{
// We matched all characters. Only if the word isn't finished it is unique
unique = validChar(haystack.charAt(j+k));
break;
}
if (needle.charAt(k) != haystack.charAt(j+k))
{
break;
}
}
}
else
{
previousValid = nextValid;
15
}
}
return unique;
}
private static boolean validChar(char c)
{
return Character.isAlphabetic(c);
}
}
a) Problem:
To develop a program that finds if a given number is odd or even.
b) Algorithm:
Exercise: Study the code, then generate an equivalent algorithm.
c) Implementation
public class FindingOddEvenNumbers
{
public static void main(String[] args)
{
//create an array of 10 numbers
int[] numbers = new int[]{1,2,3,4,5,6,7,8,9,10};
if(numbers[i]%2 == 0)
System.out.println(numbers[i] + " is even number.");
else
System.out.println(numbers[i] + " is odd number.");
}
}
}
Exercise
Modify the program so that it receives the input of the value to check from the keyboard.
16