25
Name: Dela Cruz, Arvin Dominic B. Date : Course/Year : BSCpE 4 th yr. Laboratory Exercises No 1 (Finals) Direction: Show your program output and write your code, on the space provided. Compute the discount price of a TV depending on its sizes, color, and price following the given data below: TV Type Size Price % Discount Colored 14 & 20 inches 8,500 & 15,500 10% & 12% Black & White 21 & 25 inches 3,500 & 5,000 15% & 18% Program: import javax.swing.*; class gui2 { public static void main (String [ ] args) { String type, strsize; int size ; int price; double disc_price = 0; type = JOptionPane.showInputDialog("Enter the type of TV [B] or [C]"); if (type.equals("c")) { strsize = JOptionPane.showInputDialog("Enter the inches [14 or 20]"); size = Integer.parseInt(strsize); if (size == 14) { price = 8500; disc_price=(price - (price * .10)); JOptionPane.showMessageDialog(null,"TV type : " + type + "\n" + "Price : " + price + "\n" + "Size : " + size + "\n" + "Di scount price is " + disc_price);

Finals OOP activity

Embed Size (px)

Citation preview

Name: Dela Cruz, Arvin Dominic B. Date :

Course/Year : BSCpE – 4th yr.

Laboratory Exercises No 1

(Finals)

Direction: Show your program output and write your code, on the space provided.

Compute the discount price of a TV depending on its sizes, color, and price following the given data below:

TV Type Size Price % Discount

Colored 14 & 20 inches 8,500 & 15,500 10% & 12%

Black & White 21 & 25 inches 3,500 & 5,000 15% & 18%

Program:

import javax.swing.*;

class gui2

{

publ ic s tatic void main (String [ ] args )

{

String type, s trs ize;

int s ize ;

int price;

double disc_price = 0;

type = JOptionPane.showInputDia log("Enter the type of TV [B] or [C]");

i f (type.equals ("c"))

{

s trs ize = JOptionPane.showInputDia log("Enter the inches [14 or 20]");

s i ze = Integer.parseInt(s trs ize);

i f (s i ze == 14)

{

price = 8500;

disc_price=(price - (price * .10));

JOptionPane.showMessageDia log(nul l ,"TV type : " +

type + "\n" + "Price : " + price + "\n" + "Size : " + s ize + "\n" + "Discount

price i s " + disc_price);

}

else

{

price = 15500;

s i ze = 20;

disc_price=(price - (price * .12));

JOptionPane.showMessageDia log(nul l ,"TV type : " +

type + "\n" + "Price : " + price + "\n" + "Size : " + s ize + "\n" + "Discount

price i s " + disc_price);

}

}

else

{

s trs ize = JOptionPane.showInputDia log("Enter the inches [21 or 25]");

s i ze = Integer.parseInt(s trs ize);

i f (s i ze == 21)

{

price = 3500;

disc_price=(price - (price * .15));

JOptionPane.showMessageDia log(nul l ,"TV type : " + type + "\n" +

"Price : " + price + "\n" + "Size : " + s ize + "\n" +

"Discount price i s " + disc_price);

}

else

{

price = 5000;

s i ze = 25;

disc_price=(price - (price * .18));

JOptionPane.showMessageDia log(nul l ,"TV type : " + type + "\n" +

"Price : " + price + "\n" + "Size : " + s ize + "\n" +

"Discount price i s " + disc_price);

}

}

JOptionPane.showMessageDia log(nul l ,"HAPPY BUYING");

Sys tem.exi t(0);

}

}

Screen Output:

SELF CHECK NO 10.1 – USER INTERFACE: API & GUI

DIRECTIONS: Show the screen output of the following program. Write your answer in the box provided.

1. Create an API program that will ask the user to enter a grades obtained in a two quizzes. Compute the

final grade of a student by getting the 40% of the first quiz and the 60% of second quiz. If the final grade is greater than or equal 75, display the message “ PASSED “, otherwise display the message “ FAILED “.

import java.io.*;

public class api

{

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

{

BufferedReader pasok = new BufferedReader (new InputStreamReader(System.in));

String quiz1, quiz2;

double q1,q2,finalav;

System.out.println("ENTER QUIZ # 1 \n");

quiz1 = pasok.readLine();

q1 = Double.parseDouble(quiz1);

System.out.println("ENTER QUIZ # 2 \n");

quiz2 = pasok.readLine();

q2 = Double.parseDouble(quiz2);

finalav = ((q1*.40) + (q2 * .60));

System.out.println("FINAL QUIZ # 2 \n" + finalav );

if (finalav >=75.0)

{

System.out.println("PASSED");

}

else

{

System.out.println("FAILED");

}

}

Output

2. GUI Java program that will ask the user to enter a name of the item, its price, and the number of items

being sold. Compute the total amount bought by the customer. If the customer’s total amount is more than 1, 000, a 3% discount is given. Display the discounted price to be paid by the customer and its change.

import javax.swing.*;

public class gui3

{

public static void main(String [ ] args)

{

String sName, sPrice, sItems, sCash;

double price, item, total, cash, sukli;

JOptionPane.showMessageDialog(null, "WELCOME TO LOA MALL");

sName = JOptionPane.showInputDialog("Enter the Product Name");

sPrice = JOptionPane.showInputDialog("Enter the Price");

sItems = JOptionPane.showInputDialog("Enter the number of Items Sold");

price = Double.parseDouble(sPrice);

item = Double.parseDouble(sItems);

total = price * item;

sCash = JOptionPane.showInputDialog("Enter cash tendered");

cash = Double.parseDouble(sCash);

sukli = cash - total;

JOptionPane.showMessageDialog(null, "PRODUCT NAME : " + sName + "\n" +

"PRICE : " + price + "\n" +

"ITEMS : " + item + "\n" +

"AMOUNT : " + total + "\n\n" +

"CHANGE : " + sukli);

System.exit(0);

}

}

Output

SELF CHECK NO 10.2 – USER INTERFACE: API & GUI

DIRECTIONS: Solve the following problems using API & GUI interfaces and show your program output and

code on the space provided.

1. Create a Java program to determine the name of the list of student grades for the period of Prelim, Midterm, Pre-final and Final. By using the following:

Pts. Equivalent : 100-99 = 1.0 98-96 = 1.25 95-93 = 1.50 92-90 = 1.75 89-87 = 2.0 86-84 = 2.25 83-81 = 2.50 80-78 = 2.75

77-75 = 3.0 74- below = Failed

Formula : (Pre * .2) + (Mid * .2) + (PreFi * .2) + (Final * .4)

Sample Output Name of Student :

Course : Subject :

Grade Sheet Record 2. Write a program that will ask the user to enter the six (6) subjects and its corresponding grade. You are

required to display the 6 subjects opposite their grades after the input procedure. Compute and display

the average. Program: import java.util.Scanner;

class UserInteraction {

public static void main(String[] args) { Scanner scan = new Scanner(System.in);

int choice = 0; String[] subjects = new String[6]; int grades[] = new int[6];

double sum = 0.0; do

{ System.out.println("1. Enter the subject and Grade"); System.out.println("2. Display all grades");

System.out.println("3. Calculate the average grade"); System.out.println("4. Exit program");

choice = scan.nextInt(); if ( choice == 1 )

{ Scanner scansubjects = new Scanner(System.in); Scanner scangrades = new Scanner(System.in);

System.out.println("Enter 6 subjects and their corresponding grades:"); System.out.println();

int i = 0;

for( i = 0; i < 6; i++ ) { System.out.println("Subject:");

String temp = scansubjects.nextLine();

subjects[i] = temp.toLowerCase(); System.out.println("Grade:");

grades[i] = scangrades.nextInt();

if( i == ( subjects.length - 1 ) ) { System.out.println("Thank you!");

System.out.println(); } }

}

if ( choice == 2 ) { System.out.println("Subjects" + "\tGrades");

System.out.println("---------------------"); for(int p = 0; p < subjects.length; p++)

{ System.out.println(subjects[p] + "\t" + "\t" + grades[p]);

} }

if ( choice == 3 ) { System.out.println("Total of grades: " + getSum(grades));

System.out.println("Count of grades: " + grades.length); System.out.println("Average of grades: " + getAverage(grades)); System.out.println();

}

} while ( choice != 4);

} public static double getAverage(int[] array)

{ int sum = 0; for(int i : array) sum += i;

return ((double) sum)/array.length; }

public static double getSum(int[] array) { int sum = 0;

for (int i : array) { sum += i;

} return sum;

}

}

Output:

3. Create a Java program that would accept two integer numbers. The computer will process its sum, difference, product, and quotient of the two entered numbers. Your program should include messages, which tell the numbers being entered, and its corresponding value after the computing operation occurs.

import java.util.Scanner; public class array1

{ static int x , sum , y , sub , mul , div;

public static void main ( String args[] ) { Scanner scan = new Scanner(System.in);

System.out.print("Enter first number>:"); x = scan.nextInt();

System.out.print("Enter second number>:");

y = scan.nextInt(); sum(); subtract();

multiply(); divide(); }

public static int sum ( ) {

sum = x + y; System.out.println("The sum is >:" + sum); return sum;

} public static int subtract ( )

{ sub = x - y; System.out.println("The Difference is >:" + sub);

return sub; }

public static int multiply ( ) { mul = x * y;

System.out.println("The Product is >:" + mul); return mul; }

public static int divide ( ) {

div = x / y; System.out.println("The Quotient is >:" + div); return div;

} }

Output:

4. Write a program that will ask the user to input his birthday. An integer number should be use to assign

for the month and its date and then output the equivalent zodiac sign. Include a message “INVALID MONTH” if the entered number for the month is greater than 12.

5. Write a program that will simulate a common game Jack en Poy. The two players for this game should supply a letter P, R, or S (P-paper, R-rock, and S-scissors) one after the other.

6. Create a Java program that will compute the employee’s gross, tax withheld, and the net pay following

the formula given below.. The program will ask the user to enter the hourly pay rate and the number of

hours worked.

Formula:

Gross pay = hours x rate Net pay = gross pay – tax withheld

Withholding percentage:

10 % if gross pay is less than or equal 5000 12 % if gross pay is greater than 5000

ARRAYS

11.1 INTRODUCTION

An array is a collection of variables of the same data type referenced by a common name. Each

variable within the collection is called an array element identified by its element and a unique index. An

index is an integer from zero to 1 minus the maximum size of element in the array.

Consider the illustration below for the array myGrade:

myGrade

The above illustration states that the name of an array is myGrade with 5 array elements. Each

element can be accessed by its position number called index.

11.2 REFERENCING

Referencing the individual elements of an array can be done by specifying the array name and the

position that is enclosed by a pair of bracket [ ]. To illustrate, the five elements in the array are; myGrade[ 0],

myGrade[1], myGrade[2], myGrade[3], myGrade[4]. The values of these elements are:

myGrade[0] = 78

myGrade[1] = 90

myGrade[2] = 89

myGrade[3] = 88

myGrade[4] = 80

11.3 Types of An Array

1. One dimensional Array Syntax: data type variable name [ ] = new data type [size];

2. Multi-dimensional Array Syntax: data type variable name [ ] [ ] = new data type [size] [size] ;

where:

data type = any valid data type that will hold the values of an array.

Variable name = valid identifier which will name the array

size = defines the number of elements the array will hold.

11.4 Declaring an Array by Example

Example 1:

Declare a five-element integer type array with a name myGrade.

Ans. int myGrade [ ] = new int [5];

Example 2:

An array declaration for array name quiz with a size of 4 and array name items with a size of 10, both

declared as float.

Ans. float quiz [ ] = new int [4];

float items [ ] = new int [10];

Example 3:

Declare a two-dimensional array of integer type with a name myGrade. The first dimension consists of three

array elements and the second dimension consists of 4 elements.

0 1 2

0

myGrade 1

2

3

Ans. int grade [ ] [ ] = new int [3] [4]

Example 4:

Declare a three-dimensional array of integer type with a name myGrade. The first dimension consists of

three array elements, second dimension consists of 4 elements, and the third dimension consists of 6

elements.

Ans. int grade [ ] [ ] [ ] = new int [3] [4] [6];

11.5 ARRAY INITIALIZATION

Initialization is the process of placing an initial value in the memory by assigning the value

to either a variable or an array element. Assignment operator ( = ) is used to assigned a value to a

variable. Array initialization is different; you place the lists of initial values of each array elements within the

braces and separated by a commas. Consider the example below;

int myGrade [ ] = { 78, 90, 89, 88, 80 };

As you can see on the given example above, you will notice that the array element is not explicitly

specified. The number of initial values implies the size of an array, meaning, the number of elements in the

array will serve as its array size, in this case is five. A comma within the curly braces separates each array

element. The new is not use because sufficient memory is allocated using the initial values to determine

the size of the array.

11.6 VALUES ASSIGNED TO ARRAY ELEMENTS

An element of an array is used in an expression the same as to how a variable is used in an

expression. The only difference between a variable and an array element is that, both the array name and

the index must be specified. Consider the example below;

1. int myGrade [0] = 78; 2. int myGrade [0] [2] = 95;

3. int myGrade [1] [2] = myGrade [1] [5]; The value assigned to the array myGrade on the first example is 90 and is place on the first element.

The value assigned to a two-dimensional array myGrade on the second example is 95, and is place on the

first column – third row. The last example assign a value located at the second column – sixth row, and

place it on the second column – third row position using the same array name.

Example 1: Write a program that will print the values of the array name myGrade. The array elements are; 78, 90, 89,

88, and 80 accordingly.

Program: public class array1

{

public static void main(String [ ] args)

{

int myGrade [ ] = {78, 90, 89, 88, 80};

int x;

for (x = 0;x<5;x++)

{

System.out.println("My Grades " + x + " is " + myGrade[x]);

}

}

}

Output:

Example 2:

Write a program that will accept 5 grades obtain by the student. Display the entered grade and compute its

average.

Program: import java.io.*;

public class array2

{

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

{

BufferedReader pasok = new BufferedReader (new InputStreamReader(System.in));

String myGrade [ ] = new String [5];

int grade [ ] = new int [5];

int x;

double totgr=0, aver=0;

System.out.print("GRADING SYSTEM \n\n");

for (x=0;x<5;x++)

{

System.out.print("Enter your grade #" + (x+1) + " ");

myGrade[x] = pasok.readLine();

grade[x] = Integer.parseInt(myGrade[x]);

totgr+=grade[x];

aver=(totgr/5);

}

for (x = 0;x<5;x++)

{

System.out.println( "\nGrade #" + (x+1) + " is " + grade[x]);

}

System.out.println("\n\nAVERAGE " + aver);

}

}

Output:

11.7 SORT AND BINARY SEARCH

Sorting values of array is one of the basic things you’ll do with an array. This can be done by calling

the sort() method of the Array class. Sorting is arranging the values of the elements in the array by

ascending or descending order.

Binary Search on the other hand is used to locate an array element that contains a particular

value. The binarySearch() method will find the value in the array. This method requires that the array be

sorted before the search begins; otherwise, the binary search won’t be able to locate the value.

Example 3: Write a program that will arrange the obtained grades of the student from lowest to highest. Display the

ordered grades and compute its average grade. The grades will be entered by the user.

Program:

import java.util.*;

import java.io.*;

public class array3

{

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

{

BufferedReader pasok = new BufferedReader (new InputStreamReader(System.in));

String myGrade [ ] = new String [5];

int grade [ ] = new int [5];

int x;

double totgr=0, aver=0;

System.out.print("GRADING SYSTEM \n\n");

for (x=0;x<5;x++)

{

System.out.print("Enter your grade #" + (x+1) + " ");

myGrade[x] = pasok.readLine();

grade[x] = Integer.parseInt(myGrade[x]);

totgr+=grade[x];

aver=(totgr/5);

}

Arrays.sort(grade);

for (x = 0;x<5;x++)

{

System.out.println( "\nGrades arranged in order " + grade[x]);

}

System.out.println("\n\nAVERAGE " + aver);

}

}

Output:

Example 4: Write a program that will arrange a five-element string inputted by the user and arranged it in ascending

order. The computer will ask to enter a string and searches its index location. Display the location of the

string found.

Program:

import java.util.*;

import java.io.*;

public class array4

{

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

{

BufferedReader pasok = new BufferedReader (new InputStreamReader(System.in));

String myName [ ] = new String [5];

int loc, x,y=0;

String hanapName;

System.out.print("SEARCHING THE ELEMENTS\n\n");

for (x=0;x<5;x++)

{

System.out.print("Enter a String Element " + x + " ");

myName[x] = pasok.readLine();

}

Arrays.sort(myName);

System.out.print("\n\nSORTED STRING ELEMENTS\n\n");

for (x = 0;x<5;x++)

{

System.out.println( "Element " + x + " " + myName[x]);

}

System.out.print("\nEnter Element to search ");

hanapName = pasok.readLine();

loc = Arrays.binarySearch(myName,hanapName);

if (loc >=0)

{

System.out.println("\nElement "+hanapName + " is located at index number " + loc);

}

else

{

System.out.println("\n"+hanapName + " is NOT AN ELEMENT");

}

}

}

Output:

SELF CHECK NO 11.1 – ARRAYS

DIRECTIONS: Show the screen output of the following program. Write your answer in the box provided.

1. Create a Java program that will print the values of the following one-dimensional array name my_Number with elements 45, 56, 45, 98, 12, 14, and 9.

public class array1{

public static void main(String [ ] args) {

int my_Number [ ] = {45,56,45,98,12,14,9};

int x;

for (x = 0;x<my_Number.length;x++)

{

System.out.println("My Grades " + (x+1) + " is " + my_NUmber[x]); }

}

}

Output

SELF CHECK NO 11.2 – ARRAYS

DIRECTIONS: Solve the following problems using Arrays.

1. Create a Java program that will print the values and compute its average of the following array: int number[6] = { 88, 90, 78, 83, 89, 90}

Program: class Array1{ public static void main(String[] args) { double nums[]={88, 90, 78, 83, 89, 90}; double result=0.0; int i=0; System.out.println("Values = 88, 90, 78, 83, 89, 90"); for(i=0; i < nums.length; i++){ result=result + nums[i]; } System.out.println("Average is =" + result/nums.length); } }

2. Write a program that will search for the largest and smallest value in a 12 data array element. Elements

should be entered by the user during run-time.

Program:

import java.util.Scanner; public class array1

{

public static void main( String[] args )

{ Scanner input = new Scanner( System.in );

int number1; int number2;

int number3; int number4; int number5;

int number6; int number7; int number8;

int number9; int number10; int number11;

int number12; int largest; int smallest;

System.out.print( "Enter first integer: " ); number1 = input.nextInt();

System.out.print( "Enter second integer: " ); number2 = input.nextInt();

System.out.print( "Enter third integer: " ); number3 = input.nextInt();

System.out.print( "Enter fourth integer: " ); number4 = input.nextInt();

System.out.print( "Enter fifth integer: " ); number5 = input.nextInt();

System.out.print( "Enter sixth integer: " ); number6 = input.nextInt();

System.out.print( "Enter seventh integer: " ); number7 = input.nextInt();

System.out.print( "Enter eighth integer: " ); number8 = input.nextInt();

System.out.print( "Enter nineth integer: " ); number9 = input.nextInt();

System.out.print( "Enter tenth integer: " ); number10 = input.nextInt();

System.out.print( "Enter eleventh integer: " ); number11 = input.nextInt();

System.out.print( "Enter twelfth integer: " ); number12 = input.nextInt();

smallest = number1;

if ( number2 < smallest ) smallest = number2; if ( number3 < smallest )

smallest = number3; if ( number4 < smallest ) smallest = number4;

if ( number5 < smallest ) smallest = number5;

if ( number6 < smallest ) smallest = number6;

if ( number7 < smallest ) smallest = number7;

if ( number8 < smallest ) smallest = number8;

if ( number9 < smallest ) smallest = number9;

if ( number10 < smallest ) smallest = number10;

if ( number11 < smallest ) smallest = number11;

if ( number12 < smallest ) smallest = number12; largest = number1;

if ( number2 > largest ) largest = number2; if ( number3 > largest )

largest = number3; if ( number4 > largest ) largest = number4;

if ( number5 > largest ) largest = number5; if ( number6 > largest )

largest = number6; if ( number7 > largest ) largest = number7;

if ( number8 > largest ) largest = number8; if ( number9 > largest )

largest = number9; if ( number10 > largest ) largest = number10;

if ( number11> largest ) largest = number11; if ( number12 > largest )

largest = number12; System.out.printf( "Smallest is %d\n", smallest ); System.out.printf( "Largest is %d\n", largest );

}

}

Output:

3. Create a GUI Java program that will ask the user to enter the total items and its correct answers on the

five subject examination using one-dimensional array. Compute and display its equivalent grade for

each subject and the average grade of all the subjects using the given formula below; a. grade = (score/items) * 50 +50 b. average = the sum of all grade divided by the number of subjects

Program: import java.util.Scanner; // program uses class Scanner

public class array1 {

// main method begins execution of Java application public static void main( String[] args ) {

// create a Scanner to obtain input from command window Scanner input = new Scanner( System.in );

int number1; // first integer to use in computations int number2; // second integer to use in computations int number3; // third integer to use in computations

int number4; // fourth integer to use in computations int number5; // fifth integer to use in computations int sum; // sum of number1, number2, number3, number4, and number5

int avg; // average of number1, number2, number3, number4, and number5

System.out.print( "Enter the grade in 1st subject: " ); // prompt number1 = input.nextInt(); // read first number from user

System.out.print( "Enter the grade in 2nd subject " ); // prompt number2 = input.nextInt(); // read second number from user

System.out.print( "Enter the grade in 3rd subject " ); // prompt number3 = input.nextInt(); // read third number from user

System.out.print( "Enter the grade in 4th subject" ); // prompt number4 = input.nextInt(); // read fourth number from user

System.out.print( "Enter the grade in 5th subject " ); // prompt number5 = input.nextInt(); // read fifth number from user

sum = ( number1 + number2 + number3 + number4 + number5 ); // add the five numbers, store total in sum

avg = ( ( sum ) / 5 ); // divide sum of five numbers by 5 for average, store result in avg

System.out.printf( "Average is %d\n", avg ); // display average

} // end method main

} // end class LargeSmall

4. Write a Java program that will arrange the following students name in alphabetical order.

String my_Name [5] = { Yulo, Mario, Danilo, Sam, Aldrin}

Program:

class array1

{

public static void main(String[ ] args)

{

String[ ] names = {"Yulo", "Mario", "Danilo", "Sam", "Aldrin"};

sortStringBubble (names);

for ( int k = 0; k < 4; k++ )

System.out.println( names [ k ] );

}

public static void sortStringBubble( String x [ ] )

{

int j;

boolean flag = true; // will determine when the sort is finished

String temp;

while ( flag )

{

flag = false;

for ( j = 0; j < x.length - 1; j++ )

{

if ( x [ j ].compareToIgnoreCase( x [ j+1 ] ) > 0 )

{ // ascending sort

temp = x [ j ];

x [ j ] = x [ j+1]; // swapping

x [ j+1] = temp;

flag = true;

}

}

}

}

}

Output: