COMP 231 LAB SOLUTIONS Prepared by : Sewar Abueid LAB NO.2: Question One: (calculate BMI): //////////////////////////////////////////////////////////////////////// import java.util.Scanner; public class Selection { public static void main(String [] args) { Scanner input =new Scanner(System.in); System.out.println("Enter your weight in kilograms please :"); double Weight_In_KiloGrams=input.nextDouble(); System.out.println("Enter your length in cm please :"); double Length_In_Meters=input.nextDouble(); // convert the weight to pounds: double pound=Weight_In_KiloGrams*2.2; // convert the length to meters : double inches= Length_In_Meters*0.39; double BMI=(pound*703)/(inches*inches); System.out.println("BMI is \t"+BMI); if(15<=BMI&&BMI<19) { System.out.println("UNDERWEIGHT"); } else if(19<=BMI && BMI<25) { System.out.println("NORMAL"); } else if(25<=BMI && BMI<30) { System.out.println("OVERWEIGHT"); } else System.out.println("Something wrong!!!!!Check of your data and try again !"); input.close(); } } ///////////////////////////////////////////////////////////////////////////////// Question Two: (Salary for Employees): import java.util.Scanner; public class ComputingSalary { public static void main(String[] args) { Scanner input=new Scanner(System.in); int stop=0; while (stop!=-1) { System.out.println("Enter your hourworked or -1 to stop"); int hourWorked=input.nextInt(); if(hourWorked!=-1) { System.out.println("Enter your hour rate :"); double hourRate=input.nextDouble(); if(hourWorked<=40) { System.out.println("your salary is"+(hourWorked*hourRate)); } else if(hourWorked>40) { double salary=(hourWorked*hourRate)+((hourWorked-40)*hourRate*0.5); System.out.println("your salary is"+salary); } else { System.out.println("Somthing wrong ! check your data"); } } else if(hourWorked==-1) { stop=-1; } } input.close(); } } /////////////////////////////////////////////////////////////////////////////////// Question Three : (Prime number) : import java.util.Scanner; public class PrimeNumber { public static void main(String[] args) { int counter=0; Scanner input=new Scanner(System.in); boolean prime; for(int i=2;i<500;i++) { prime =isPrime(i); if(prime==true) System.out.println(i); } // Now we want to improve the program to test the entered number whether it is prime or not: System.out.println("enter the number to test or less than two to end :"); int number=input.nextInt(); while(number>2) { for(int i=1;i<=number;i++) { if(number%i==0) counter++; } if(counter ==2) { System.out.println("the number is prime"); } else { System.out.println("The number is not prime"); } System.out.println("Enter a number to test or less than 2 to end"); int num=input.nextInt(); if(num<2) number=0; } input.close(); } public static boolean isPrime(int number) { int count=0; for(int j=1;j<=number;j++) { if(number%j==0) count++; } if(count==2) return true; else return false; } } ////////////////////////////////////////////////////////////////////////////////////////////// LAB NO.3 Question One :(Find the exponential) : import java.util.Scanner; public class Exponential { public static void main(String [] args) { Scanner input=new Scanner(System.in); System.out.println("Enter the number that you want to find the exponential for :"); int num=input.nextInt(); double answer=exp(num); System.out.println("The answer is "+answer); input.close();} public static double exp(int x) { double summation=0; summation=1+(x)+((x*x)/fact(2))+((x*x*x)/fact(3))+((x*x*x*x)/fact(4))+((x*x*x*x*x)/fact(5)); return summation; } public static double fact (int x) { double result=1; for(int i=1;i<=x;i++) { result=result*i; } return result; } } ////////////////////////////////////////////////////////////////////////////////////////////////// Question Two :(Perfect Number) : import java.util.Scanner; public class PerfectNumber { public static void main(String [] args) { Scanner input=new Scanner(System.in); for(int i=1;i<=1000;i++) { if(isPrime(i)) { System.out.println(i); } } // This part is to check whether the entered number by the user is perfect or no int count=0; System.out.println("Please enter the number :"); int x=input.nextInt(); for(int j=1;j>>>>>>>>>> The complement: input.close(); } public static boolean isPrime(int x) { int count=0; for(int i=1;i>> Question Three complement :Additional Task (Decimal To Binary): import java.util.Scanner; public class DecimalToBinary { public static void main(String[] args) { Scanner input=new Scanner(System.in); int i=0; int binary []=new int [100]; System.out.println("Enter the number in decimal to convert to Binary : "); int number =input.nextInt(); while(number!=0) { binary[i]=number%2; i++; number=number/2; } for(int j=i-1;j>=0;j--) System.out.print(binary[j]); input.close(); } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// LAB NO.4 : Question One : Building (This solution is before modifying)(هذا حل أول فرع من السؤال ): import java.util.Scanner; public class Building { public static void main(String[] args) { Scanner input=new Scanner(System.in); System.out.println("Enter the number of appartments :"); int numOfapart=input.nextInt(); int [] Building=new int[numOfapart]; for(int i=0;iavg) { count1++; } else if(Building[i]empWithLargestSalary.getBasicSalary()) empWithLargestSalary=emp[i]; } return empWithLargestSalary; } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Question Two : // this is the MyArray class public class MyArray { // the internal of this class is an array of integers int [] array; // the constructors as shown in the lab manual are only a parameterised constructor: public MyArray(int [] newArray) { array=newArray; } // this is the min method that will return the minimum element in the array public int min() { int minimum=array[0]; for(int i=0;imaximum) maximum=array[i]; } return maximum; } // this is the avg method that will return the average of the values in the array public double avg() { int sum=0; double average; for(int i=0;i=3) count++; } return count; } } ///////////////// and Now this is The Tester class ,, implement it in a separated file : public class TestString { public static void main(String [] args) { System.out.println(MyString.reverseString("Hello")); System.out.println(MyString.isPalindrom("madam I'm adam")); System.out.println(MyString.shortHanded("if you are " + "one for them and I will to")); System.out.println("The number of sent is "+ MyString.numOfSent("Hi! How are you? I hope you are " + "fine.")); System.out.println("The number of sent is "+ MyString.numOfWords("Sewar is One of " + "IT collegue students")); } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Question Two : Encrypt: //// The Solution : is just One class with main method public class Encrypt { public static void main(String [] args) { String toUpper=toUpperMethod("I Love java"); String rev=reverseString(toUpper); String toNum=toNumbers(rev); String addStars=beginAndEnd(toNum); System.out.println("your encrypted sentence is :"+addStars); } public static String toUpperMethod(String s) { return s.toUpperCase(); } public static String reverseString(String s) { StringBuilder stb=new StringBuilder(s); return stb.reverse().toString(); } public static String toNumbers(String s) { s=s.replace('S', '$'); s=s.replace('L', '1'); s=s.replace('O', '0'); return s; } public static String beginAndEnd(String s) { String s2=" *** "+s+" *** "; return s2; } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// LAB NO.7: Inheritance and Polymorphism ///////////Question one :(Account Class ): //////هذا اللاب هو سؤال واحد فقط ونريد إنشاء ثلاثة كلاسات وكلاس الفحص سؤال سهل جدا وسريع: //////////////////// Solution : /////////////////////Class number one : public class Account { protected int id=0; protected double balance=0; protected java.util.Date dateCreated; public Account() { dateCreated=new java.util.Date(); dateCreated.getTime(); } public Account(int id,double balance) { this.id=id; this.balance=balance; dateCreated=new java.util.Date(); dateCreated.getTime(); } public int getId() { return id; } public void setId(int id) { this.id = id; } public double getBalance() { return balance; } public void setBalance(double balance) { this.balance = balance; } public java.util.Date getDateCreated() { return dateCreated; } public double withDraw(double specificAmount) { if(specificAmount0) { balance =balance-specificAmount; return balance; } else if(balance -specificAmount<0) { this.balance+=overDraft; if(balance-specificAmount>0) { balance-=specificAmount; return balance; } else { return balance; } } else { balance=0; return balance; } } @Override public String toString() { return "Checking [overDraft=" + overDraft + ", id=" + id + ", balance=" + balance + ", dateCreated=" + dateCreated + "]"; } } /////////////////////////////////////////////////////////////////////////Class number three : public class Saving extends Account{ public Saving(int id,double balance) { super(id,balance); } @Override public double withDraw(double specificAmount) { if(balance-specificAmount>0) { balance=balance-specificAmount; return balance; } else return balance; } @Override public String toString() { return "Saving [id=" + id + ", balance=" + balance + ", dateCreated=" + dateCreated + "]"; } } ////////////////////////////////////////////////////////////// class number four (Driver): public class TestAccount { public static void main(String [] args) { Account a1=new Account(1200043,1000); a1.deposite(1000); a1.withDraw(1500); System.out.println(a1.toString()); Checking c1=new Checking(120123,1500); c1.deposite(100); System.out.println(c1.toString()); c1.withDraw(1700); System.out.println(c1.toString()); Saving s1=new Saving(1200000,3000); s1.withDraw(4000); System.out.println(s1.toString()); } } ////////////////////////////////////// Note: يمكنك تغيير القيم التي تريدها في الكلاس الأخير وهو كلاس الفحص حتى تتأكد من الية عمل جميع الميثودس /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// LAB NO.8 : //Question One (Employees classes) : // The solution : // Note that this exercise defines six Classes ,the five classes in the UML notation in the lab manual and the Test class : // class number one : public abstract class Employee implements Comparable{ public String firstName; public String lastName; public int ID; public Employee() { } public Employee(String firstName,String lastName,int ID) { this.firstName=firstName; this.lastName=lastName; this.ID=ID; } public abstract double earning(); @Override public int compareTo(Employee emp) { if(emp.earning()>this.earning()) return 1; else if (emp.earning()>this.earning()) return -1; else return 0; } } ////////////////////////////////////////////////// class number Two : public class SalariedEmployee extends Employee{ public double weeklySalary; public SalariedEmployee() { } public SalariedEmployee(String firstName,String lastName,int ID, double weeklySalary) { super(firstName,lastName,ID); this.weeklySalary=weeklySalary; } public double getWeeklySalary() { return weeklySalary; } public void setWeeklySalary(double weeklySalary) { this.weeklySalary = weeklySalary; } public double earning() { return (getWeeklySalary()*4); } @Override public String toString() { return "SalariedEmployee [weeklySalary=" + weeklySalary + ", earning()=" + earning() + "]"; } } ////////////////////////////////////////////////////////////////////////////// Class Number Three : public class HourlyEmployee extends Employee { public double wage; public int numOfHoursWorked; public HourlyEmployee() { } public HourlyEmployee(String firstName,String lastName,int ID, double wage,int numOfHoursWorked) { super(firstName,lastName,ID); this.wage=wage; this.numOfHoursWorked=numOfHoursWorked; } public double getWage() { return wage; } public void setWage(double wage) { this.wage = wage; } public int getNumOfHoursWorked() { return numOfHoursWorked; } public void setNumOfHoursWorked(int numOfHoursWorked) { this.numOfHoursWorked = numOfHoursWorked; } @Override public double earning() { return (getWage()*getNumOfHoursWorked()); } @Override public String toString() { return "HourlyEmployee [wage=" + wage + ", numOfHoursWorked=" + numOfHoursWorked + ", getWage()=" + getWage() + ", getNumOfHoursWorked()=" + getNumOfHoursWorked() + ", earning()=" + earning() + "]"; } } ////////////////////////////////////////////////////////////////////////////////////// class number four : public class CommisionEmployee extends Employee { public double rate; public double grossSales; public CommisionEmployee() { } public CommisionEmployee(String firstName, String lastName, int ID ,double rate,double grossSales) { super(firstName, lastName, ID); this.rate=rate; this.grossSales=grossSales; } public double getRate() { return rate; } public void setRate(double rate) { this.rate = rate; } public double getGrossSales() { return grossSales; } public void setGrossSales(double grossSales) { this.grossSales = grossSales; } @Override public double earning() { return (getRate()*getGrossSales()); } @Override public String toString() { return "CommisionEmployee [rate=" + rate + ", grossSales=" + grossSales + ", getRate()=" + getRate() + ", getGrossSales()=" + getGrossSales() + ", earning()=" + earning() + "]"; } } ///////////////////////////////////////////////////////////////////////// class number five : public class BaseCommisionEmployee extends CommisionEmployee{ public double baseSalary; public BaseCommisionEmployee() { } public BaseCommisionEmployee(String firstName, String lastName, int ID, double rate, double grossSales,double base) { super(firstName, lastName, ID, rate, grossSales); this.baseSalary=base; } public double getBaseSalary() { return baseSalary; } // implement getSalary @Override public double earning() { return(getRate()*getGrossSales()+getBaseSalary()); } @Override public String toString() { return "BaseCommisionEmployee [baseSalary=" + baseSalary + ", getBaseSalary()=" + getBaseSalary() + ", earning()=" + earning() + "]"; } } //////////////////////////////////////////////////////////////// class number six and this is the last class for Testing (Driver) : public class TestEmployee { public static void main(String[] args) { Employee [] emp= {new SalariedEmployee("Sewar"," AbuEid",120,1000), new CommisionEmployee("Qamar","Arab",133,10,1200), new HourlyEmployee("Bushra","Wesam",100,30,10), new BaseCommisionEmployee("Mariam","Wesam",122,15,1000,20) ,new HourlyEmployee("Lana","Amjad",110,15,250)}; System.out.println("The total earnings is "+totalEarnings(emp)); sort(emp); } public static double totalEarnings(Employee [] a) { double total=0; for(int i=0;i { private String color; private boolean filled; public Shape() { } public Shape(String color,boolean filled) { this.color=color; this.filled=filled; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public boolean isFilled() { return filled; } public void setFilled(boolean filled) { this.filled = filled; } @Override public String toString() { return "Shape [color=" + color + ", filled=" + filled + "]"; } public abstract double getArea(); public abstract String ClassName(); @Override public int compareTo(Shape s) { if(s.getArea()> this.getArea()) return 1; else if(s.getArea() shapes=new ArrayList<>(); shapes.add(new Circle(4,"red",false)); shapes.add(new Circle(10,"Black",true)); shapes.add(new Rectangle(5,7)); shapes.add(new Rectangle(1.5,0.3)); shapes.add(new Circle(3.5,"Orange",false)); java.util.Collections.sort(shapes); for(int i=0;i{c1.setFill(Color.RED); c2.setFill(null); c3.setFill(null);}); rbtnyellow.setOnAction(e->{c2.setFill(Color.YELLOW); c1.setFill(null); c3.setFill(null); }); rbtngreen.setOnAction(e->{c3.setFill(Color.color(0,1,0)); c1.setFill(null); c2.setFill(null); }); /////////////////////// Scene sc=new Scene(lightPane,400,500); stage.setScene(sc); stage.setTitle("Traffic signal"); stage.show(); } catch(Exception ex) { ex.printStackTrace(); } } public static void main(String [] args ) { launch(args); } } //////////////////////////////////////////////////////////////////////////////////////////////// Question Two : // The solution : package application; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.layout.GridPane; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.stage.Stage; public class ChessBoard extends Application{ @Override public void start(Stage primaryStage) { GridPane pn=new GridPane(); int count=0; for(int i=0;i<8;i++) { count++; for(int j=0;j<8;j++) { Rectangle r=new Rectangle(25,25); if(count%2==0) r.setFill(Color.WHITE); pn.add(r, i, j); count++; } } Scene sc=new Scene(pn,200,200); primaryStage.setTitle("Chess Board"); primaryStage.setResizable(false); primaryStage.setScene(sc); primaryStage.show(); } public static void main(String[] args) { launch(args); } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Question Three : Note: this question will be completed in the next lab, here I solved it completely .you will divide this solution for two labs . // The solution : package application; import javafx.application.Application; import javafx.stage.Stage; import javafx.scene.Scene; import javafx.scene.control.TextField; import javafx.scene.control.Label; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.control.RadioButton; import javafx.scene.control.ToggleGroup; import javafx.geometry.Pos; import javafx.geometry.Insets; import javafx.scene.input.KeyCode; public class SettingOfAText extends Application { TextField txt = new TextField(); TextField txtSize = new TextField(); @Override public void start(Stage primaryStage) { txt.setText("Java is Amazing ! "); // set the position for text Fields txt.setAlignment(Pos.BOTTOM_CENTER); txtSize.setAlignment(Pos.BOTTOM_RIGHT); txtSize.setPrefColumnCount(3); txt.setPrefColumnCount(12); txtSize.setText("12"); // Create radio buttons RadioButton rbtnLeft = new RadioButton("Left"); RadioButton rbtnCenter = new RadioButton("Center"); RadioButton rbtnRight = new RadioButton("Right"); // rbtnCenter.setSelected(true); // Create a toggle group for the radio button ToggleGroup group = new ToggleGroup(); rbtnLeft.setToggleGroup(group); rbtnCenter.setToggleGroup(group); rbtnRight.setToggleGroup(group); HBox hb1 = new HBox(10); hb1.getChildren().addAll(rbtnLeft, rbtnCenter, rbtnRight); hb1.setAlignment(Pos.BOTTOM_LEFT); // this hbox is for the label and the textField that contains the size HBox hb2 = new HBox(5); Label lb=new Label("column Size :"); hb2.getChildren().addAll(lb, txtSize); HBox hb3 = new HBox(5); hb3.setAlignment(Pos.CENTER); Label lb2=new Label("Text Field : "); hb3.getChildren().addAll(lb2, txt); HBox hbox = new HBox(10); hbox.getChildren().addAll(hb1, hb2); // Create a vBox and place nodes in it VBox pane = new VBox(10); pane.setPadding(new Insets(10, 10, 10, 10)); pane.getChildren().addAll(hb3, hbox); /* * Handling with the radio Buttons */ rbtnLeft.setOnAction(e -> { if (rbtnLeft.isSelected()) { txt.setAlignment(Pos.BOTTOM_LEFT); } }); rbtnCenter.setOnAction(e -> { if (rbtnCenter.isSelected()) { txt.setAlignment(Pos.BOTTOM_CENTER); } }); rbtnRight.setOnAction(e -> { if (rbtnRight.isSelected()) { txt.setAlignment(Pos.BOTTOM_RIGHT); } }); txtSize.setOnKeyPressed(e -> { if (e.getCode() == KeyCode.ENTER) // you must press enter to display your new size { txt.setPrefColumnCount(Integer.parseInt( txtSize.getText())); } }); // Create a scene and place it in the stage Scene scene = new Scene(pane); primaryStage.setTitle("Exercise_16_06"); primaryStage.setScene(scene); primaryStage.show(); } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// LAB NO.11 : // Question 1 & 2 are solved above .... in the previous lab ////// Question Three : package application; import java.io.File; import java.io.FileWriter; import java.io.PrintWriter; import javafx.application.Application; import javafx.geometry.Insets; import javafx.stage.Stage; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.RadioButton; import javafx.scene.control.TextField; import javafx.scene.control.ToggleGroup; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; public class Main extends Application { @Override public void start(Stage primaryStage) { try { // Creating GridPane and specify its properties GridPane root = new GridPane(); root.setHgap(10); root.setVgap(10); root.setPadding(new Insets(15,15,15,15)); // create the UI as shown in the lab manual and put them in the grid pane Label lb1=new Label("StudentID :"); TextField txt1=new TextField(); root.add(lb1,0, 0); root.add(txt1, 1, 0); Label lb2=new Label("Student Name :"); TextField txt2=new TextField(); root.add(lb2, 0, 1); root.add(txt2, 1, 1); Label lb3=new Label("Average :"); root.add(lb3, 0, 2); // Three radio buttons for the averages : RadioButton rbtn1=new RadioButton("Excellent"); RadioButton rbtn2=new RadioButton("very good"); RadioButton rbtn3=new RadioButton("Good"); /// creating the toggle group for the three radio buttons : ToggleGroup group=new ToggleGroup(); rbtn1.setToggleGroup(group); rbtn2.setToggleGroup(group); rbtn3.setToggleGroup(group); HBox hb=new HBox(5); hb.getChildren().addAll(rbtn1,rbtn2,rbtn3); root.add(hb, 1, 2); Label lb4=new Label("Departement Name :"); TextField txt4=new TextField(); root.add(lb4, 0, 3); root.add(txt4, 1, 3); Button btn=new Button("Add "); root.add(btn, 0, 4); // Button Handling FileWriter myWriter=new FileWriter(new File ("result.txt")); PrintWriter write=new PrintWriter(myWriter); btn.setOnAction(e->{ String avg; int id=Integer.parseInt(txt1.getText()); String name=txt2.getText(); if(rbtn1.isSelected()) { avg="Excellent"; } else if(rbtn2.isSelected()){ avg="VeryGood"; } else if(rbtn3.isSelected()){ avg="Good"; } else { avg="No average has been choosen"; } String depName=txt4.getText(); write.println("Name : "+name+" ID : "+id+" Average : " + avg+" departement Name : "+depName); write.close(); }); Scene scene = new Scene(root,450,250); primaryStage.setScene(scene); primaryStage.setTitle("Add Student "); primaryStage.show(); } catch(Exception e) { e.printStackTrace(); } } public static void main(String[] args) { launch(args); } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////