0% found this document useful (0 votes)
25 views

BSCS 208 AOOP Lab Programming Examples

The document provides code examples and explanations for 7 Java programs: 1) Hello World, 2) Distance Converter, 3) Calculator, 4) GUI Calculator, 5) Multiplication Table, 6) Factorial, and 7) Number Reversing. For each program, it outlines the problem, provides the code solution, and exercises for the reader to generate the algorithm or modify the code.

Uploaded by

craigcarlos95
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

BSCS 208 AOOP Lab Programming Examples

The document provides code examples and explanations for 7 Java programs: 1) Hello World, 2) Distance Converter, 3) Calculator, 4) GUI Calculator, 5) Multiplication Table, 6) Factorial, and 7) Number Reversing. For each program, it outlines the problem, provides the code solution, and exercises for the reader to generate the algorithm or modify the code.

Uploaded by

craigcarlos95
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

SIT 600 PROBLEM SOLVING WITH PROGRAMMING – WORKED OUT PROGRAMS

1: Hello world

a) Problem:
To develop an application that prints the message “Hello World!!!”

b) Algorithm:
Print the message “Hello World!!!”

c) Implementation:

public class HelloWorld


{
public static void main(String[]args)
{
System.out.println("Hello World!!!");// prints Hello World
}
}

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

public class DistanceConverter


{
//void main
public static void main (String[] args)
{
//declare float
float to,from;
//print message
System.out.println("Enter Length in meter:");
//Take input
Scanner input = new Scanner(System.in);
//calculate
from = input.nextFloat();
to = from/1000;
//print the average
System.out.println("Length in kilometer = "+to);
}
}

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.

3: Calculator (demonstrating the switch statement)

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;

public class Calc


{
public static void main(String args[])
{
float a, b, res;
char choice, ch;
Scanner scan = new Scanner(System.in);

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

4. Calculator (GUI Version)

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:

1. Create the following GUI


a. Open a New Project in NetBeans
b. In the New Project Dialog Box, select Java application, then click Next
c. Enter the project name as MathCalculatorUI
d. Deselect the “Create Main Class” check box then click Finish.
e. In the Projects tab, right-click on Source Packages of the application, then select New
Folder
f. Enter the name of the new folder as my.mathcalculatorui
g. Right-click on the grayed my.MathCalculatorUI folder and choose JFrame Form
h. Enter a name for the form as MathCalculatorUI then click Finish
i. Insert GUI components from your toolbox palette on the right hand as desired using
drag-drop. NB: You should do something like the following figure.

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());

// Now we can perform the addition.


result = num1+num2;

// We will now pass the value of result to jTextField3.


// At the same time, we are going to change the value of result from a float to a string.
jTextField3.setText(String.valueOf(result));
}
if (jRadioButton2.isSelected())
{
num1 = Float.parseFloat(jTextField1.getText());
num2 = Float.parseFloat(jTextField2.getText());

// Now we can perform the addition.


result = num1-num2;

// We will now pass the value of result to jTextField3.


// At the same time, we are going to change the value of result from a float to a string.

5
jTextField3.setText(String.valueOf(result));
}
if (jRadioButton3.isSelected())
{
num1 = Float.parseFloat(jTextField1.getText());
num2 = Float.parseFloat(jTextField2.getText());

// Now we can perform the addition.


result = num1*num2;

// We will now pass the value of result to jTextField3.


// At the same time, we are going to change the value of result from a float to a string.
jTextField3.setText(String.valueOf(result));
}
if (jRadioButton4.isSelected())
{
num1 = Float.parseFloat(jTextField1.getText());
num2 = Float.parseFloat(jTextField2.getText());

// Now we can perform the addition.


result = num1/num2;

// We will now pass the value of result to jTextField3.


// At the same time, we are going to change the value of result from a float to a string.
jTextField3.setText(String.valueOf(result));
}
}
catch (NumberFormatException e)
{
}

Code for Clear button


jTextField1.setText("");
jTextField2.setText("");
jTextField3.setText("");

Code for Exit button


System.exit(0);

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:

public class NumberFactorial


{
public static void main(String[] args)
{
int number = 7;
int factorial = number;
for(int i =(number - 1); i > 1; i--)
{
factorial = factorial * i;
}
System.out.println("Factorial of a number is " + factorial);
}
}

Exercise
Modify the code so that the program receives the user desired number before computing the factorial.

7. Number Reversing Program

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;
}

System.out.println("Reversed Number is: " + reversedNumber);


}
}

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

public class SimpleStringTokenizerAndCountDemo


{
public static void main(String[] args)
{
// creating string tokenizer
StringTokenizer st = new StringTokenizer("Tutorialspoint is the best site");

// counting tokens
System.out.println("Total tokens : " + st.countTokens());
}
}

10. Split Tokens with ‘@’ as the delimiter

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

public class SplitTokens1


{
public static void main(String args[])
{
//String str = "geekss@for@geekss";
String str = "fools@forget@their@destiny";
String [] arrOfStr = str.split("@");

//String str = "geekss for geekss";


//String [] arrOfStr = str.split(" ");

for (String a : arrOfStr)


System.out.println(a);
}
}

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

public class TellingTypeOfCharacter


{
public static void main(String[] args)
{
char letter;
do
{
letter=(char)(java.lang.Math.random()*128);
if (letter < ' ')
System.out.println(" Non printing");
else if ((letter >= 'a') && (letter <= 'z'))
System.out.println(letter + " Lower case");
else if ((letter >= 'A') && (letter <= 'Z'))
System.out.println(letter +" Upper case");
else if ((letter >= '0') && (letter <= '9'))
System.out.println(letter +" Digit");
else
switch(letter)
{
case '.':System.out.println("Fullstop");
case ',':System.out.println("Comma");
case '$':System.out.println("Dollar");
case '~':System.out.println("Tilde");
default :System.out.println("Some other symbol");
}
}
while(letter != 'q');
}
}

12. Temperature converter

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;

double celsius = ( 5.0 * (fahrenheit - 32.0) ) / 9.0;

System.out.println(fahrenheit + " F is same as " + celsius + " C.");

}
}

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.

13. Sorting Cities

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;

for(int i=0; i<size; i++)


{
for(int j=i+1; j<size; j++)
{
if(city[j].compareTo(city[i]) < 0)
{
temp = city[i];
city[i] = city[j];
city[j] = temp;
}

11
}
}
for (int i=0; i<size; i++)
{
System.out.println(city[i]);
}
}
}

14. Common Subexpression Eliminator

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

Vector L = new Vector();

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

for(int i=0;i < L.size();i++)


{
if((L.elementAt(i)).equals(r))
flag=true; //If Expression already present in Vector do nothing

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
*/

15. Counting Unique Characters in a String

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 = "";

for (int i = 0; i < str.length(); i++)


{
if(temp.indexOf(str.charAt(i)) == -1 )
{

13
temp = temp + str.charAt(i);
}
}
System.out.println(temp);
System.out.println("Unique character count: " + temp.length());
}
}

16. Counting Unique Tokens in a String

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

public class CountingUniqueTokensInString


{
public static void main(String[] args)
{
String inputPhrase = "one two one two three one";
countWords(inputPhrase);
}

private static void countWords(String inputPhrase)


{
boolean increment = false;
int wordStart = -1;
int phraseWordCount = 0;
int uniqueWordCount = 0;
for (int i = 0; i < inputPhrase.length(); i++)
{
//validChar(char c) is a simple method that returns a valid character
if(validChar(inputPhrase.charAt(i)))
{
increment = true;
if(wordStart == -1)
{
wordStart = i;
}
}
else if(increment)
{
phraseWordCount++;
final String lastWord = inputPhrase.substring(wordStart, i);

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

17. Finding if given number is odd or even

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};

for(int i=0; i < numbers.length; i++)


{
/*
Use modulus operator to check if the number is even or odd.
If we divide any number by 2 and reminder is 0 then the number is
even, otherwise it is odd.
*/

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

You might also like