├── lecture-notes
├── JVM.docx
├── ArrayList.docx
├── GUI_Basics.ppt
├── Design_Pattern.pdf
├── Design_patterns.docx
├── Java_Collection.docx
├── Language_Keywords.docx
├── SOLID_principles.docx
├── Event-Driven_Programming.ppt
├── Creating_User_Interfaces_Swing.ppt
└── Inheritance_Association_Composition_Delegation.docx
├── lab-08-mysql
├── mysql-shell.png
├── screenshot-1.png
├── screenshot-2.png
├── U1910049_Lab_8_JDBC.zip
├── 08-_Lab_Assignment_-_APJ_-_JDBC.docx
└── IUT_BMI.java
├── jdbc-tutorial
├── JDBCExample.class
├── Handy_MySQL_Commands.docx
├── Readme.md
├── JdbcSelectTest_insert.java
├── JDBCExample.java
└── JdbcSelectTest.java
├── lab-06-swing
├── U1910049_Lab#6.zip
├── 06-_Lab_Assignment_-_APJ_-_GUI_basics_and_Event_Handling.docx
├── Printer.java
└── Calculator.java
├── lab-10-multithreading
├── screenshot.png
├── U1910049_Lab10.zip
├── 10-_Lab_Assignment_-_APJ_-_MULTITHREADING.docx
└── PrimeNum.java
├── lab-01
├── 01_-_Lab_Assignment_-_APJ.docx
└── BMI.java
├── lab-05
├── out
│ └── production
│ │ └── lab-05
│ │ ├── TV.class
│ │ ├── Mobile.class
│ │ ├── Product.class
│ │ ├── Operatable.class
│ │ └── ProductDemo.class
├── 05-_Lab_Assignment_-_APJ_-_abstract_interface_polymorphism.docx
├── lab-05.iml
└── src
│ └── ProductDemo.java
├── lab-07-javafx
├── U1910049_Lab_7_JavaFX.zip
├── 07-_Lab_Assignment_-_APJ_-_GUI_Using_JAVAFX.docx
├── PrinterJavaFX.java
└── CalculatorJavaFX.java
├── java-collection
├── Queue Interface In Java.docx
├── Why use PreparedStatement.docx
└── collections-framework.md
├── lab-09-networking
├── server-client-networking.png
├── U1910049_Lab_9_Networking.zip
├── Lab_-09_-_APJ_-_Network_Programming.docx
├── Server.java
└── Client.java
├── java-multithreading
├── Multithreading in Java.docx
├── Runnable.java
├── Readme.md
├── MultiThreadTest.java
├── ClientAB.java
├── Client.java
├── MultiThreadServerAB.java
└── MultiThreadServer.java
├── javafx-tutorial
├── JavaFX_Tutorial_-_Jakob_Jenkov.docx
├── install Run javaFX apps.txt
├── ButtonExperiments.java
├── MyFxApp.java
├── JavaFXLayoutDemo.java
└── EventFiltersExample.java
├── lab-04
├── 04-_Lab_Assignment_-_APJ_-_Inheritance.docx
└── DoMApplication.java
├── lab-02
├── 02-_Lab_Assignment_-_APJ_-_BMI_Interpretation.docx
├── App_2.0.java
└── App.java
├── lab-03
├── 03-_Lab_Assignment_-_APJ_-_Mobile_TestMobile-_class_object.docx
└── MobileTest.java
├── lab-00
├── Welcome.java
├── UserInput.java
├── DisplayUnicode.java
├── ComputeArea.java
├── FahrenheitToCelsius.java
├── ComputeAreaWithConsoleInput.java
└── ShowCurrentTime.java
├── java-swing-tutorial
├── MyFrame.java
├── MyFrame1.java
├── MyFrameWithComponents.java
├── ShowBorderLayout.java
├── ShowGridLayout.java
├── ShowFlowLayout.java
├── TestPanels.java
├── HandleEvent1.java
├── HandleEvent.java
├── ShowGridBagLayout.java
└── java-swing.md
├── java-networking
├── InetDemo.java
├── ClientAB.java
├── ServerAB.java
├── Server.java
├── Client.java
└── URLDemo.java
├── midterm-exam
├── RemoveDuplicate.java
├── MatrixMultiplication.java
├── Account.java
└── BankAccount.java
├── template-menus
├── TemplateMenu.java
└── TemplateMenu2.java
└── README.md
/lecture-notes/JVM.docx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rustam-Z/java-programming/HEAD/lecture-notes/JVM.docx
--------------------------------------------------------------------------------
/lab-08-mysql/mysql-shell.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rustam-Z/java-programming/HEAD/lab-08-mysql/mysql-shell.png
--------------------------------------------------------------------------------
/lecture-notes/ArrayList.docx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rustam-Z/java-programming/HEAD/lecture-notes/ArrayList.docx
--------------------------------------------------------------------------------
/lecture-notes/GUI_Basics.ppt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rustam-Z/java-programming/HEAD/lecture-notes/GUI_Basics.ppt
--------------------------------------------------------------------------------
/jdbc-tutorial/JDBCExample.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rustam-Z/java-programming/HEAD/jdbc-tutorial/JDBCExample.class
--------------------------------------------------------------------------------
/lab-06-swing/U1910049_Lab#6.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rustam-Z/java-programming/HEAD/lab-06-swing/U1910049_Lab#6.zip
--------------------------------------------------------------------------------
/lab-08-mysql/screenshot-1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rustam-Z/java-programming/HEAD/lab-08-mysql/screenshot-1.png
--------------------------------------------------------------------------------
/lab-08-mysql/screenshot-2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rustam-Z/java-programming/HEAD/lab-08-mysql/screenshot-2.png
--------------------------------------------------------------------------------
/lecture-notes/Design_Pattern.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rustam-Z/java-programming/HEAD/lecture-notes/Design_Pattern.pdf
--------------------------------------------------------------------------------
/lab-08-mysql/U1910049_Lab_8_JDBC.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rustam-Z/java-programming/HEAD/lab-08-mysql/U1910049_Lab_8_JDBC.zip
--------------------------------------------------------------------------------
/lab-10-multithreading/screenshot.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rustam-Z/java-programming/HEAD/lab-10-multithreading/screenshot.png
--------------------------------------------------------------------------------
/lecture-notes/Design_patterns.docx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rustam-Z/java-programming/HEAD/lecture-notes/Design_patterns.docx
--------------------------------------------------------------------------------
/lecture-notes/Java_Collection.docx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rustam-Z/java-programming/HEAD/lecture-notes/Java_Collection.docx
--------------------------------------------------------------------------------
/lecture-notes/Language_Keywords.docx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rustam-Z/java-programming/HEAD/lecture-notes/Language_Keywords.docx
--------------------------------------------------------------------------------
/lecture-notes/SOLID_principles.docx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rustam-Z/java-programming/HEAD/lecture-notes/SOLID_principles.docx
--------------------------------------------------------------------------------
/lab-01/01_-_Lab_Assignment_-_APJ.docx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rustam-Z/java-programming/HEAD/lab-01/01_-_Lab_Assignment_-_APJ.docx
--------------------------------------------------------------------------------
/lab-05/out/production/lab-05/TV.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rustam-Z/java-programming/HEAD/lab-05/out/production/lab-05/TV.class
--------------------------------------------------------------------------------
/jdbc-tutorial/Handy_MySQL_Commands.docx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rustam-Z/java-programming/HEAD/jdbc-tutorial/Handy_MySQL_Commands.docx
--------------------------------------------------------------------------------
/lab-05/out/production/lab-05/Mobile.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rustam-Z/java-programming/HEAD/lab-05/out/production/lab-05/Mobile.class
--------------------------------------------------------------------------------
/lab-07-javafx/U1910049_Lab_7_JavaFX.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rustam-Z/java-programming/HEAD/lab-07-javafx/U1910049_Lab_7_JavaFX.zip
--------------------------------------------------------------------------------
/lab-10-multithreading/U1910049_Lab10.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rustam-Z/java-programming/HEAD/lab-10-multithreading/U1910049_Lab10.zip
--------------------------------------------------------------------------------
/lab-05/out/production/lab-05/Product.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rustam-Z/java-programming/HEAD/lab-05/out/production/lab-05/Product.class
--------------------------------------------------------------------------------
/lecture-notes/Event-Driven_Programming.ppt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rustam-Z/java-programming/HEAD/lecture-notes/Event-Driven_Programming.ppt
--------------------------------------------------------------------------------
/java-collection/Queue Interface In Java.docx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rustam-Z/java-programming/HEAD/java-collection/Queue Interface In Java.docx
--------------------------------------------------------------------------------
/java-collection/Why use PreparedStatement.docx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rustam-Z/java-programming/HEAD/java-collection/Why use PreparedStatement.docx
--------------------------------------------------------------------------------
/lab-05/out/production/lab-05/Operatable.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rustam-Z/java-programming/HEAD/lab-05/out/production/lab-05/Operatable.class
--------------------------------------------------------------------------------
/lab-05/out/production/lab-05/ProductDemo.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rustam-Z/java-programming/HEAD/lab-05/out/production/lab-05/ProductDemo.class
--------------------------------------------------------------------------------
/lab-09-networking/server-client-networking.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rustam-Z/java-programming/HEAD/lab-09-networking/server-client-networking.png
--------------------------------------------------------------------------------
/java-multithreading/Multithreading in Java.docx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rustam-Z/java-programming/HEAD/java-multithreading/Multithreading in Java.docx
--------------------------------------------------------------------------------
/lab-09-networking/U1910049_Lab_9_Networking.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rustam-Z/java-programming/HEAD/lab-09-networking/U1910049_Lab_9_Networking.zip
--------------------------------------------------------------------------------
/lecture-notes/Creating_User_Interfaces_Swing.ppt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rustam-Z/java-programming/HEAD/lecture-notes/Creating_User_Interfaces_Swing.ppt
--------------------------------------------------------------------------------
/javafx-tutorial/JavaFX_Tutorial_-_Jakob_Jenkov.docx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rustam-Z/java-programming/HEAD/javafx-tutorial/JavaFX_Tutorial_-_Jakob_Jenkov.docx
--------------------------------------------------------------------------------
/lab-04/04-_Lab_Assignment_-_APJ_-_Inheritance.docx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rustam-Z/java-programming/HEAD/lab-04/04-_Lab_Assignment_-_APJ_-_Inheritance.docx
--------------------------------------------------------------------------------
/lab-08-mysql/08-_Lab_Assignment_-_APJ_-_JDBC.docx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rustam-Z/java-programming/HEAD/lab-08-mysql/08-_Lab_Assignment_-_APJ_-_JDBC.docx
--------------------------------------------------------------------------------
/lab-02/02-_Lab_Assignment_-_APJ_-_BMI_Interpretation.docx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rustam-Z/java-programming/HEAD/lab-02/02-_Lab_Assignment_-_APJ_-_BMI_Interpretation.docx
--------------------------------------------------------------------------------
/lab-09-networking/Lab_-09_-_APJ_-_Network_Programming.docx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rustam-Z/java-programming/HEAD/lab-09-networking/Lab_-09_-_APJ_-_Network_Programming.docx
--------------------------------------------------------------------------------
/lab-07-javafx/07-_Lab_Assignment_-_APJ_-_GUI_Using_JAVAFX.docx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rustam-Z/java-programming/HEAD/lab-07-javafx/07-_Lab_Assignment_-_APJ_-_GUI_Using_JAVAFX.docx
--------------------------------------------------------------------------------
/lecture-notes/Inheritance_Association_Composition_Delegation.docx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rustam-Z/java-programming/HEAD/lecture-notes/Inheritance_Association_Composition_Delegation.docx
--------------------------------------------------------------------------------
/lab-10-multithreading/10-_Lab_Assignment_-_APJ_-_MULTITHREADING.docx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rustam-Z/java-programming/HEAD/lab-10-multithreading/10-_Lab_Assignment_-_APJ_-_MULTITHREADING.docx
--------------------------------------------------------------------------------
/lab-03/03-_Lab_Assignment_-_APJ_-_Mobile_TestMobile-_class_object.docx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rustam-Z/java-programming/HEAD/lab-03/03-_Lab_Assignment_-_APJ_-_Mobile_TestMobile-_class_object.docx
--------------------------------------------------------------------------------
/lab-05/05-_Lab_Assignment_-_APJ_-_abstract_interface_polymorphism.docx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rustam-Z/java-programming/HEAD/lab-05/05-_Lab_Assignment_-_APJ_-_abstract_interface_polymorphism.docx
--------------------------------------------------------------------------------
/lab-06-swing/06-_Lab_Assignment_-_APJ_-_GUI_basics_and_Event_Handling.docx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Rustam-Z/java-programming/HEAD/lab-06-swing/06-_Lab_Assignment_-_APJ_-_GUI_basics_and_Event_Handling.docx
--------------------------------------------------------------------------------
/lab-00/Welcome.java:
--------------------------------------------------------------------------------
1 | // Java program to print text "Welcome to java!"
2 |
3 | /*
4 | Student : Rustam
5 | Student Id : U1910000
6 | */
7 |
8 | public class Welcome
9 | {
10 | public static void main(String args[])
11 | {
12 | System.out.println("Welcome to Java!");
13 | }
14 | }
--------------------------------------------------------------------------------
/lab-00/UserInput.java:
--------------------------------------------------------------------------------
1 | // First Program
2 | import java.util.Scanner;
3 |
4 | class UserInput{
5 | public static void main(String[] args) {
6 | Scanner id = new Scanner(System.in);
7 | System.out.print("Hello Rustam! Enter a word: ");
8 | System.out.println(id.nextLine());
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/lab-00/DisplayUnicode.java:
--------------------------------------------------------------------------------
1 | import javax.swing.JOptionPane;
2 |
3 | public class DisplayUnicode {
4 | public static void main(String[] args) {
5 | JOptionPane.showMessageDialog(null,
6 | "\u6B22\u8FCE \u03b1 \u03b2 \u03b3",
7 | "\u6B22\u8FCE Welcome",
8 | JOptionPane.INFORMATION_MESSAGE);
9 | }
10 | }
--------------------------------------------------------------------------------
/java-swing-tutorial/MyFrame.java:
--------------------------------------------------------------------------------
1 | package programs;
2 |
3 | import javax.swing.*;
4 |
5 | public class MyFrame {
6 | public static void main(String[] args) {
7 | JFrame frame = new JFrame("Test Frame");
8 | frame.setSize(400, 300);
9 | frame.setLocationRelativeTo(null);
10 | frame.setVisible(true);
11 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
12 | }
13 | }
--------------------------------------------------------------------------------
/lab-00/ComputeArea.java:
--------------------------------------------------------------------------------
1 | public class ComputeArea {
2 | public static void main(String[] args) {
3 | double radius; // Declare radius
4 | double area; // Declare area
5 |
6 | // Assign a radius
7 | radius = 20; // New value is radius
8 |
9 | // Compute area
10 | area = radius * radius * 3.14159;
11 |
12 | // Display results
13 | System.out.println("The area for the circle of radius " +
14 | radius + " is " + area);
15 | }
16 | }
--------------------------------------------------------------------------------
/java-collection/collections-framework.md:
--------------------------------------------------------------------------------
1 | ## Collections Framework
2 | > Java Collection framework provides many interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet etc).
3 |
4 | - [Lecture Notes](lecture-notes/Java_Collection.docx)
5 |
6 | - Readymade architecture, no need to implement functions
7 |
8 | - `ArrayList` uses an `Object[]`, and makes a bigger array when the array gets full.
9 |
10 |
--------------------------------------------------------------------------------
/lab-05/lab-05.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/java-networking/InetDemo.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.net.*;
3 |
4 | public class InetDemo {
5 | public static void main(String[] args) {
6 | try{
7 | InetAddress ip=InetAddress.getByName("www.google.com");
8 | System.out.println("Host Name: "+ip.getHostName());
9 | System.out.println("IP Address: "+ip.getHostAddress());
10 | }
11 | catch(Exception e) {
12 | System.out.println(e);
13 | }
14 | }
15 | }
--------------------------------------------------------------------------------
/lab-00/FahrenheitToCelsius.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class FahrenheitToCelsius {
4 | public static void main(String[] args) {
5 | Scanner input = new Scanner(System.in);
6 |
7 | System.out.print("Enter a degree in Fahrenheit: ");
8 | double fahrenheit = input.nextDouble();
9 |
10 | // Convert Fahrenheit to Celsius
11 | double celsius = (5.0 / 9) * (fahrenheit - 32);
12 | System.out.println("Fahrenheit " + fahrenheit + " is " +
13 | celsius + " in Celsius");
14 | }
15 | }
--------------------------------------------------------------------------------
/java-multithreading/Runnable.java:
--------------------------------------------------------------------------------
1 | class thread1 implements Runnable
2 | {
3 | public void run()
4 | {
5 | System.out.println("Thread1");
6 | }
7 |
8 | public static void main(String[] arg)
9 | {
10 | thread1 obj1=new thread1();
11 | Thread t= new Thread(obj1);
12 | t.start();
13 | }
14 | }
15 |
16 | /*
17 | class thread1 extends Thread
18 | {
19 | public void run()
20 | {
21 | System.out.println("Thread1");
22 | }
23 |
24 | public static void main(String[] arg)
25 | {
26 | thread1 obj1=new thread1();
27 | obj1.start();
28 | }
29 | }*/
--------------------------------------------------------------------------------
/java-swing-tutorial/MyFrame1.java:
--------------------------------------------------------------------------------
1 | package programs;
2 |
3 | import javax.swing.*;
4 |
5 | public class MyFrame1 extends JFrame {
6 |
7 | public MyFrame1() {
8 | super("MyFrame");
9 |
10 | setSize(400, 300); // Set the frame size
11 | setLocationRelativeTo(null); // New since JDK 1 s
12 | setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
13 | setVisible(true); // Display the frame
14 | }
15 |
16 | public static void main(String[] args) {
17 | MyFrame1 frame = new MyFrame1(); // Create a frame
18 | }
19 | }
--------------------------------------------------------------------------------
/midterm-exam/RemoveDuplicate.java:
--------------------------------------------------------------------------------
1 | import java.util.ArrayList;
2 |
3 | public static void removeDuplicate(ArrayList list) {
4 | // Create a new ArrayList
5 | ArrayList newList = new ArrayList();
6 | // Traverse through the first list
7 | for (Integer element : list) {
8 | // If this element is not present in newList
9 | // then add it
10 | if (!newList.contains(element)) {
11 | newList.add(element);
12 | }
13 | }
14 |
15 | // return the new list
16 | return newList;
17 | }
--------------------------------------------------------------------------------
/java-swing-tutorial/MyFrameWithComponents.java:
--------------------------------------------------------------------------------
1 | package programs;
2 |
3 | import javax.swing.*;
4 |
5 | public class MyFrameWithComponents {
6 | public static void main(String[] args) {
7 | JFrame frame = new JFrame( "MyFrameWithComponen");
8 |
9 | JButton jbtOK = new JButton("OK"); // Add a button into the frame
10 | frame.add(jbtOK); // or we can use frame.add(new Button("OK"))
11 |
12 | frame.setSize(400, 300);
13 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
14 | frame.setLocationRelativeTo(null); // Center the frame
15 | frame.setVisible(true);
16 | }
17 | }
--------------------------------------------------------------------------------
/lab-00/ComputeAreaWithConsoleInput.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner; // Scanner is in the java.util package
2 |
3 | public class ComputeAreaWithConsoleInput
4 | {
5 | public static void main(String[] args)
6 | {
7 | // Create a Scanner object
8 | Scanner input = new Scanner(System.in);
9 |
10 | // Prompt the user to enter a radius
11 | System.out.print("Enter a number for radius: ");
12 | double radius = input.nextDouble();
13 |
14 | // Compute area
15 | double area = radius * radius * 3.14159;
16 |
17 | // Display result
18 | System.out.println("The area for the circle of radius " +
19 | radius + " is " + area);
20 | }
21 | }
--------------------------------------------------------------------------------
/midterm-exam/MatrixMultiplication.java:
--------------------------------------------------------------------------------
1 | public class Matrix {
2 |
3 | public static double[][] multiplyMatrix(double[][] a, double[][] b) {
4 | // write your matrix multiplication code here
5 |
6 | int c[][]=new int[2][2];
7 |
8 | for(int i=0; i<2; i++){
9 | for(int j=0; j<2; j++){
10 | c[i][j]=0;
11 | for(int k=0; k<2; k++)
12 | c[i][j] += a[i][k]*b[k][j];
13 | System.out.print(c[i][j]);
14 | }
15 | }
16 |
17 | for(int i=0; i<2; i++){
18 | for(int j=0; j<2; j++){
19 | System.out.print(c[i][j]);
20 | }
21 | }
22 |
23 |
24 | }
25 |
26 | public static void main(String[] args) {
27 |
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/jdbc-tutorial/Readme.md:
--------------------------------------------------------------------------------
1 | # MySQL
2 |
3 | - How to open MySQL command line: https://www.tutorialspoint.com/how-to-open-mysql-command-line-on-windows10
4 |
5 | - Key points:
6 | - Connection between application and database
7 | - How to retrieve the data from database
8 | - How to insert data into database
9 |
10 | - JBDC - Java Database Connectivity
11 |
12 | - `set path=%path%;C:\mysql-connector-java-5.1.49;`
13 |
14 | - `javac -cp "C:\mysql-connector-java-5.1.49\mysql-connector-java-5.1.49-bin.jar;" JDBCExample.java`
15 |
16 | - `executeUpdate() `: This method is used for execution of DML statement(INSERT, UPDATE and DELETE) which is return int value, count of the affected rows.
17 |
18 | - `executeQuery()` : This method is used to retrieve data from database using SELECT query.
19 |
--------------------------------------------------------------------------------
/javafx-tutorial/install Run javaFX apps.txt:
--------------------------------------------------------------------------------
1 | Download an appropriate JavaFX runtime for your operating system and unzip it to a desired location. For this tutorial, we will be using JavaFX .
2 |
3 | Add an environment variable pointing to the lib directory of the runtime: (e.g. you have download and unziped "javafx-sdk-11.0.2")
4 |
5 |
6 | set PATH_TO_FX="C:\Program Files\javafx-sdk-11.0.2\lib"
7 |
8 | You can now compile and run JavaFX applications from the command line using the JavaFX runtime.
9 |
10 | Compile the application (e.g. use HelloFX.java from this sample) using:
11 |
12 | javac --module-path %PATH_TO_FX% --add-modules javafx.controls HelloFX.java
13 |
14 | Run the application (e.g. use HelloFX.java from this sample) using:
15 |
16 | java --module-path %PATH_TO_FX% --add-modules javafx.controls HelloFX
17 |
18 | reference : https://openjfx.io/openjfx-docs/#install-javafx
--------------------------------------------------------------------------------
/lab-00/ShowCurrentTime.java:
--------------------------------------------------------------------------------
1 | public class ShowCurrentTime
2 | {
3 | public static void main(String[] args) {
4 | // Obtain the total milliseconds since midnight, Jan 1, 1970
5 | long totalMilliseconds = System.currentTimeMillis();
6 |
7 | // Obtain the total seconds since midnight, Jan 1, 1970
8 | long totalSeconds = totalMilliseconds / 1000;
9 |
10 | // Compute the current second in the minute in the hour
11 | long currentSecond = (int)(totalSeconds % 60);
12 |
13 | // Obtain the total minutes
14 | long totalMinutes = totalSeconds / 60;
15 |
16 | // Compute the current minute in the hour
17 | long currentMinute = (int)(totalMinutes % 60);
18 |
19 | // Obtain the total hours
20 | long totalHours = totalMinutes / 60;
21 |
22 | // Compute the current hour
23 | long currentHour = (int)(totalHours % 24);
24 |
25 | // Display results
26 | System.out.println("Current time is " + currentHour + ":"
27 | + currentMinute + ":" + currentSecond + " GMT");
28 | }
29 | }
--------------------------------------------------------------------------------
/java-swing-tutorial/ShowBorderLayout.java:
--------------------------------------------------------------------------------
1 | package programs;
2 |
3 | import javax.swing.JButton;
4 | import javax.swing.JFrame;
5 | import java.awt.BorderLayout;
6 |
7 | public class ShowBorderLayout extends JFrame {
8 | public ShowBorderLayout() {
9 | // Set BorderLayout with horizontal gap 5 and vertical gap 10
10 | setLayout(new BorderLayout(5, 10));
11 |
12 | // Add buttons to the frame
13 | add(new JButton("East"), BorderLayout.EAST);
14 | add(new JButton("South"), BorderLayout.SOUTH);
15 | add(new JButton("West"), BorderLayout.WEST);
16 | add(new JButton("North"), BorderLayout.NORTH);
17 | add(new JButton("Center"), BorderLayout.CENTER);
18 | }
19 |
20 | /** Main method */
21 | public static void main(String[] args) {
22 | ShowBorderLayout frame = new ShowBorderLayout();
23 | frame.setTitle("ShowBorderLayout");
24 | frame.setSize(300, 200);
25 | frame.setLocationRelativeTo(null); // Center the frame
26 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
27 | frame.setVisible(true);
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/java-swing-tutorial/ShowGridLayout.java:
--------------------------------------------------------------------------------
1 | package programs;
2 |
3 | import javax.swing.JLabel;
4 | import javax.swing.JTextField;
5 | import javax.swing.JFrame;
6 | import java.awt.GridLayout;
7 |
8 | public class ShowGridLayout extends JFrame {
9 | public ShowGridLayout() {
10 | // Set GridLayout, 3 rows, 2 columns, and gaps 5 between
11 | // components horizontally and vertically
12 | setLayout(new GridLayout(3, 2, 5, 5));
13 |
14 | // Add labels and text fields to the frame
15 | add(new JLabel("First Name"));
16 | add(new JTextField(8));
17 | add(new JLabel("MI"));
18 | add(new JTextField(1));
19 | add(new JLabel("Last Name"));
20 | add(new JTextField(8));
21 | }
22 |
23 | /** Main method */
24 | public static void main(String[] args) {
25 | ShowGridLayout frame = new ShowGridLayout();
26 | frame.setTitle("ShowGridLayout");
27 | frame.setSize(200, 125);
28 | frame.setLocationRelativeTo(null); // Center the frame
29 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
30 | frame.setVisible(true);
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/java-swing-tutorial/ShowFlowLayout.java:
--------------------------------------------------------------------------------
1 | package programs;
2 |
3 | import javax.swing.JLabel;
4 | import javax.swing.JTextField;
5 | import javax.swing.JFrame;
6 | import java.awt.FlowLayout;
7 |
8 | public class ShowFlowLayout extends JFrame {
9 | public ShowFlowLayout() {
10 | // Set FlowLayout, aligned left with horizontal gap 10
11 | // and vertical gap 20 between components
12 | setLayout(new FlowLayout(FlowLayout.LEFT, 10, 20));
13 |
14 | // Add labels and text fields to the frame
15 | add(new JLabel("First Name"));
16 | add(new JTextField(8));
17 | add(new JLabel("MI"));
18 | add(new JTextField(1));
19 | add(new JLabel("Last Name"));
20 | add(new JTextField(8));
21 | }
22 |
23 | /** Main method */
24 | public static void main(String[] args) {
25 | ShowFlowLayout frame = new ShowFlowLayout();
26 | frame.setTitle("ShowFlowLayout");
27 | frame.setSize(200, 200);
28 | frame.setLocationRelativeTo(null); // Center the frame
29 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
30 | frame.setVisible(true);
31 | }
32 | }
--------------------------------------------------------------------------------
/javafx-tutorial/ButtonExperiments.java:
--------------------------------------------------------------------------------
1 | import javafx.application.Application;
2 | import javafx.event.ActionEvent;
3 | import javafx.event.EventHandler;
4 | import javafx.scene.Scene;
5 | import javafx.scene.control.Button;
6 | import javafx.scene.control.Label;
7 | import javafx.scene.layout.HBox;
8 | import javafx.stage.Stage;
9 |
10 | public class ButtonExperiments extends Application {
11 |
12 | @Override
13 | public void start(Stage primaryStage) throws Exception {
14 | primaryStage.setTitle("HBox Experiment 1");
15 |
16 | Label label = new Label("Not clicked");
17 | Button button = new Button("Click");
18 |
19 | button.setOnAction(value -> {
20 | label.setText("Clicked!");
21 | System.out.println("Button Clicked!");
22 | });
23 |
24 | HBox hbox = new HBox(button, label);
25 |
26 | Scene scene = new Scene(hbox, 200, 100);
27 | primaryStage.setScene(scene);
28 | primaryStage.show();
29 |
30 | }
31 |
32 | public static void main(String[] args) {
33 | Application.launch(args);
34 | }
35 | }
36 |
37 |
38 |
--------------------------------------------------------------------------------
/lab-01/BMI.java:
--------------------------------------------------------------------------------
1 | // Body-Mass-Index Calculator in Java
2 |
3 | /*
4 | Student: Rustam Zokirov
5 | ID: U1910049
6 | Lab: Week#2
7 | */
8 |
9 | import java.util.Scanner; // Import the Scanner class
10 |
11 | class BMI { // Create a class Main
12 | public static void main(String[] args) { // Create main() method
13 | Scanner input = new Scanner(System.in); // Create a Scanner object
14 |
15 | System.out.println("Enter the weight (kg): ");
16 | double weight = input.nextDouble(); // Read user input
17 | System.out.println("Weight is: " + weight + "kg"); // Output user input
18 |
19 | System.out.println("Enter the height (m): ");
20 | double height = input.nextDouble(); // Read user input
21 | System.out.println("Height is: " + height + "m"); // Output user input
22 |
23 | double BMI_calc = weight/(height*height);
24 | System.out.println("BMI is: " + BMI_calc); // Output BMI
25 |
26 | System.out.println("Underweight: Under 18.5");
27 | System.out.println("Normal: 18.5-24.9 "); System.out.println("Overweight: 25-29.9");
28 | System.out.println("Obese: 30 or over");
29 |
30 | }
31 | }
--------------------------------------------------------------------------------
/java-multithreading/Readme.md:
--------------------------------------------------------------------------------
1 | # MULTITHREADING
2 | - ClientAB & MultiThreadServerAB - console app
3 | - Client & MultiThreadServer - with GUI
4 |
5 | ## Notes:
6 | - A multiprocessing system has more than two processors whereas Multithreading is a program execution technique that allows a single process to have multiple code segments.
7 | - Processes are typically independent of each other, While threads exist as the subset of a process. Threads can communicate with each other more easily than processes can, But threads are more vulnerable to problems caused by other threads in the same process.
8 | - A process is a program under execution i.e an active program. A thread is a lightweight process that can be managed independently by a scheduler. Processes require more time for context switching as they are more heavy. Threads require less time for context switching as they are lighter than processes.
9 | - Each process contains a single or multiple threads of execution. If a process has a single thread, only one action can be performed at a time. If a process has multiple threads, it can perform multiple actions at the same time. A thread is a sequence of instructions that can be executed independently from other code.
--------------------------------------------------------------------------------
/java-networking/ClientAB.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.net.*;
3 | import java.util.Scanner;
4 |
5 | public class ClientAB {
6 | private DataOutputStream toServer;
7 | private DataInputStream fromServer;
8 |
9 | public static void main(String[] args) {
10 | new ClientAB();
11 | }
12 |
13 | public ClientAB() {
14 | try {
15 | // Create a socket to connect to the server
16 | Socket socket = new Socket("localhost", 8000);
17 |
18 | Scanner sc = new Scanner(System.in);
19 | System.out.println("Please Enter radius");
20 | Double radius = sc.nextDouble();
21 |
22 | while(radius != 0){
23 | // Create an input stream to receive data from the server
24 | fromServer = new DataInputStream(socket.getInputStream());
25 |
26 | // Create an output stream to send data to the server
27 | toServer = new DataOutputStream(socket.getOutputStream());
28 | toServer.writeDouble(radius);
29 | toServer.flush();
30 | double area = fromServer.readDouble();
31 |
32 | System.out.println("Please area of cirlce" + area);
33 | System.out.println("Please Enter radius");
34 | radius = sc.nextDouble();
35 | }
36 |
37 | } catch (IOException ex) {
38 | System.out.println(ex.toString() + '\n');
39 | }
40 | }
41 | }
--------------------------------------------------------------------------------
/java-multithreading/MultiThreadTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | class thread1 implements Runnable
3 | {
4 | public void run()
5 | {
6 | for(int i=1;i<=10;i++)
7 | System.out.println("Thread1 " + i);
8 | }
9 |
10 |
11 | }
12 | class thread2 implements Runnable
13 | {
14 | public void run()
15 | {
16 | for(int j=1;j<=10;j++)
17 | System.out.println("Thread2 " + j);
18 | }
19 |
20 | }
21 |
22 |
23 | public class MultiThreadTest
24 | {
25 |
26 |
27 | public static void main(String[] arg)
28 | {
29 | thread1 t1=new thread1();
30 | thread2 t2 = new thread2();
31 |
32 | Thread thobj1 = new Thread(t1);
33 | Thread thobj2=new Thread(t2);
34 |
35 |
36 | thobj1.start();
37 | thobj2.start();
38 |
39 | }
40 | }
41 | */
42 | class thread1 extends Thread
43 | {
44 | public void run()
45 | {
46 | for(int i=1;i<=10;i++)
47 | System.out.println("Thread1 " + i);
48 | }
49 |
50 |
51 | }
52 | class thread2 extends Thread
53 | {
54 | public void run()
55 | {
56 | for(int j=1;j<=10;j++)
57 | System.out.println("Thread2 " + j);
58 | }
59 |
60 | }
61 |
62 |
63 | public class MultiThreadTest
64 | {
65 |
66 |
67 | public static void main(String[] arg)
68 | {
69 | thread1 t1=new thread1();
70 | thread2 t2 = new thread2();
71 |
72 |
73 | t1.start();
74 | t2.start();
75 |
76 | }
77 | }
78 |
79 |
80 |
--------------------------------------------------------------------------------
/java-swing-tutorial/TestPanels.java:
--------------------------------------------------------------------------------
1 | package programs;
2 |
3 | import java.awt.*;
4 | import javax.swing.*;
5 |
6 | public class TestPanels extends JFrame {
7 | public TestPanels() {
8 | // Create panel p1 for the buttons and set GridLayout
9 | JPanel p1 = new JPanel();
10 | p1.setLayout(new GridLayout(4, 3));
11 |
12 | // Add buttons to the panel
13 | for (int i = 1; i <= 9; i++) {
14 | p1.add(new JButton("" + i));
15 | }
16 |
17 | p1.add(new JButton("" + 0));
18 | p1.add(new JButton("Start"));
19 | p1.add(new JButton("Stop"));
20 |
21 | // Create panel p2 to hold a text field and p1
22 | JPanel p2 = new JPanel(new BorderLayout());
23 | p2.add(new JTextField("Time to be displayed here"), BorderLayout.NORTH);
24 | p2.add(p1, BorderLayout.CENTER);
25 |
26 | // add contents into the frame
27 | add(p2, BorderLayout.EAST);
28 | add(new JButton("Food to be placed here"), BorderLayout.CENTER);
29 | }
30 |
31 | /** Main method */
32 | public static void main(String[] args) {
33 | TestPanels frame = new TestPanels();
34 | frame.setTitle("The Front View of a Microwave Oven");
35 | frame.setSize(400, 250);
36 | frame.setLocationRelativeTo(null); // Center the frame
37 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
38 | frame.setVisible(true);
39 | }
40 | }
--------------------------------------------------------------------------------
/java-swing-tutorial/HandleEvent1.java:
--------------------------------------------------------------------------------
1 | package programs;
2 |
3 | import javax.swing.*;
4 | import java.awt.event.*;
5 |
6 | public class HandleEvent1 extends JFrame {
7 | JButton jbtOK = new JButton("OK");
8 | JButton jbtCancel = new JButton("Cancel");
9 |
10 | public HandleEvent1() {
11 | // Create a panel to hold buttons
12 | JPanel panel = new JPanel();
13 | panel.add(jbtOK);
14 | panel.add(jbtCancel);
15 |
16 | add(panel); // Add panel to the frame
17 |
18 | // Register listeners
19 | ListenerClass listener = new ListenerClass();
20 |
21 | jbtOK.addActionListener(listener);
22 | jbtCancel.addActionListener(listener);
23 | }
24 |
25 | public static void main(String[] args) {
26 | JFrame frame = new HandleEvent1();
27 | frame.setTitle("Handle Event");
28 | frame.setSize(400, 400);
29 | frame.setLocation(200, 100);
30 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
31 | frame.setVisible(true);
32 | }
33 |
34 | class ListenerClass implements ActionListener {
35 | public void actionPerformed(ActionEvent e) {
36 | if (e.getSource() == jbtOK)
37 | System.out.println("OK button clicked");
38 | else if (e.getSource() == jbtCancel)
39 | System.out.println("Cancel button clicked");
40 | }
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/template-menus/TemplateMenu.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner; // Import the Scanner class
2 |
3 | public class TemplateMenu {
4 | public static void main(String[] args) {
5 |
6 | Scanner input = new Scanner(System.in); // Create a Scanner object
7 | int option; // Initializing some variables
8 |
9 | while(true) {
10 | System.out.println("\n***** MAIN MENU *****");
11 | System.out.println("1. TV");
12 | System.out.println("2. Mobile");
13 | System.out.println("0. Exit");
14 | System.out.print("Your choice: ");
15 | option = input.nextInt(); // get user option from above menu
16 |
17 | switch (option) { // main menu
18 | case 1:
19 | System.out.println("11111...");
20 | break;
21 |
22 | case 2:
23 | System.out.println("2222...");
24 | break;
25 |
26 | case 0:
27 | System.out.println("Quitting Program...");
28 | System.exit(0); // program ends
29 | break;
30 |
31 | default:
32 | System.out.println("Please enter a valid option!");
33 | } // end of switch
34 |
35 | } // end of while
36 |
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/java-multithreading/ClientAB.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.net.*;
3 | import java.util.Scanner;
4 |
5 |
6 | public class ClientAB
7 | {
8 | private DataOutputStream toServer;
9 | private DataInputStream fromServer;
10 | public static void main(String[] args)
11 | {
12 | new ClientAB();
13 | }
14 | public ClientAB()
15 | {
16 | try
17 | {
18 | // Create a socket to connect to the server
19 | Socket socket = new Socket("localhost", 8000);
20 |
21 | Scanner sc=new Scanner(System.in);
22 | System.out.println("Please Enter radius");
23 | Double radius=sc.nextDouble();
24 | while(radius !=0)
25 | {
26 | // Create an input stream to receive data from the server
27 | fromServer = new DataInputStream(
28 | socket.getInputStream());
29 |
30 | // Create an output stream to send data to the server
31 | toServer =new DataOutputStream(socket.getOutputStream());
32 | toServer.writeDouble(radius);
33 | toServer.flush();
34 | double area = fromServer.readDouble();
35 |
36 | System.out.println("Please area of cirlce" + area);
37 | System.out.println("Please Enter radius");
38 | radius=sc.nextDouble();
39 | }
40 |
41 | }
42 | catch (IOException ex)
43 | {
44 | System.out.println(ex.toString() + '\n');
45 | }
46 | }
47 |
48 |
49 | }
--------------------------------------------------------------------------------
/lab-10-multithreading/PrimeNum.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Student: Rustam Zokirov ID: U1910049 Lab: #10
3 | */
4 |
5 | class ThreadPrime extends Thread {
6 | public void run() {
7 | int ct = 0, n = 0, i = 1, j = 1;
8 | while (n < 10) {
9 | j = 1;
10 | ct = 0;
11 | while (j <= i) {
12 | if (i % j == 0)
13 | ct++;
14 | j++;
15 | }
16 | if (ct == 2) {
17 | System.out.println("Prime: " + i);
18 | n++;
19 | }
20 | i++;
21 | try {
22 | Thread.sleep(500);
23 | } catch (InterruptedException e) {
24 | // TODO Auto-generated catch block
25 | e.printStackTrace();
26 | }
27 | }
28 | }
29 | }
30 |
31 | class ThreadNonPrime extends Thread {
32 | public void run() {
33 | int x = 18; //end of the interval
34 | int y = 2; //first of the interval
35 | for(int i = y + 1; i < x; i++) {
36 | for(int j = 2; j < i; j++) {
37 | if((i % j ==0 )) {
38 | System.out.println("Non-Prime: " + i);
39 | break;
40 | }
41 | }
42 | try {
43 | Thread.sleep(500);
44 | } catch (InterruptedException e) {
45 | // TODO Auto-generated catch block
46 | e.printStackTrace();
47 | }
48 | }
49 |
50 | }
51 | }
52 |
53 | public class PrimeNum {
54 | public static void main(String[] arg) {
55 | ThreadPrime thread1 = new ThreadPrime();
56 | ThreadNonPrime thread2 = new ThreadNonPrime();
57 |
58 | thread1.start();
59 | thread2.start();
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/java-networking/ServerAB.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.net.*;
3 | import java.util.*;
4 |
5 | public class ServerAB {
6 |
7 | public static void main(String[] args) {
8 | new ServerAB();
9 | }
10 |
11 | public ServerAB() { // constructor
12 | try {
13 | // Create a server socket
14 | ServerSocket serverSocket = new ServerSocket(8000);
15 | System.out.println("Server started at " + new Date() + '\n');
16 |
17 | // Listen for a connection request
18 | Socket socket = serverSocket.accept();
19 |
20 | // Create data input and output streams
21 | DataInputStream inputFromClient = new DataInputStream(
22 | socket.getInputStream());
23 | DataOutputStream outputToClient = new DataOutputStream(
24 | socket.getOutputStream());
25 |
26 | while (true) {
27 | // Receive radius from the client
28 | double radius = inputFromClient.readDouble();
29 |
30 | InetAddress ip = socket.getInetAddress();
31 | System.out.println("Host Name: " + ip.getHostName());
32 | System.out.println("IP Address: " + ip.getHostAddress());
33 | System.out.println("We have received radius value "+ radius);
34 |
35 | // Compute area
36 | double area = radius * radius * Math.PI;
37 |
38 | // Send area back to the client
39 | outputToClient.writeDouble(area);
40 | }
41 | } catch(IOException ex) {
42 | System.err.println(ex);
43 | }
44 | }
45 | }
--------------------------------------------------------------------------------
/java-swing-tutorial/HandleEvent.java:
--------------------------------------------------------------------------------
1 | package programs;
2 |
3 | import javax.swing.*;
4 | import java.awt.event.*;
5 |
6 | public class HandleEvent extends JFrame {
7 | public HandleEvent() {
8 | // Create two buttons
9 | JButton jbtOK = new JButton("OK");
10 | JButton jbtCancel = new JButton("Cancel");
11 |
12 | // Create a panel to hold buttons
13 | JPanel panel = new JPanel();
14 | panel.add(jbtOK);
15 | panel.add(jbtCancel);
16 |
17 | add(panel); // Add panel to the frame
18 |
19 | // Register listeners
20 | OKListenerClass listener1 = new OKListenerClass();
21 | CancelListenerClass listener2 = new CancelListenerClass();
22 | jbtOK.addActionListener(listener1);
23 | jbtCancel.addActionListener(listener2);
24 | }
25 |
26 | public static void main(String[] args) {
27 | JFrame frame = new HandleEvent();
28 | frame.setTitle("Handle Event");
29 | frame.setSize(200, 150);
30 | frame.setLocation(200, 100);
31 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
32 | frame.setVisible(true);
33 | }
34 | }
35 |
36 | class OKListenerClass implements ActionListener {
37 | public void actionPerformed(ActionEvent e) {
38 | System.out.println("OK button clicked");
39 | }
40 | }
41 |
42 | class CancelListenerClass implements ActionListener {
43 | public void actionPerformed(ActionEvent e) {
44 | System.out.println("Cancel button clicked");
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/javafx-tutorial/MyFxApp.java:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | import javafx.application.Application;
4 | import javafx.stage.Stage;
5 |
6 | public class MyFxApp extends Application {
7 |
8 | @Override
9 | public void start(Stage primaryStage) throws Exception {
10 | primaryStage.setTitle("My First JavaFX App");
11 |
12 | primaryStage.show();
13 | }
14 |
15 | }
16 |
17 | */
18 |
19 |
20 | /*
21 | import javafx.application.Application;
22 | import javafx.stage.Stage;
23 |
24 | public class MyFxApp extends Application {
25 |
26 | @Override
27 | public void start(Stage primaryStage) throws Exception {
28 | primaryStage.setTitle("My First JavaFX App");
29 |
30 | primaryStage.show();
31 | }
32 |
33 | public static void main(String[] args) {
34 | Application.launch(args);
35 | }
36 |
37 |
38 | }
39 | */
40 |
41 | import javafx.application.Application;
42 | import javafx.scene.Scene;
43 | import javafx.scene.control.Label;
44 | import javafx.stage.Stage;
45 |
46 | public class MyFxApp extends Application {
47 |
48 | @Override
49 | public void start(Stage primaryStage) throws Exception {
50 | primaryStage.setTitle("My First JavaFX App");
51 |
52 | Label label = new Label("Hello World, JavaFX !");
53 | Scene scene = new Scene(label, 400, 200);
54 | primaryStage.setScene(scene);
55 |
56 | primaryStage.show();
57 | }
58 |
59 | public static void main(String[] args) {
60 | Application.launch(args);
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Application Programming in Java
2 |
3 | Rustam_Z🚀, 9.10.2020
4 |
5 | ### Learn JAVA in 1 video
6 | - [Java in 100 seconds](https://www.youtube.com/watch?v=l9AzO1FMgM8)
7 | - [Learn Java in One Video](https://www.youtube.com/watch?v=drQK8ciCAjY)
8 |
9 | ### Reading
10 | - [javatpoint.com](https://www.javatpoint.com/java-tutorial)
11 | - [jenkov.com](https://jenkov.com/tutorials/java/strings.html)
12 | - [baeldung.com](https://www.baeldung.com/get-started-with-java-series)
13 |
14 | ### Video Tutorials
15 | - [Programming with Mosh - Programming with JAVA from scratch](https://www.youtube.com/watch?v=eIrMbAQSU34)
16 | - [Tech with Tim - More focus on data structures, collections library](https://www.youtube.com/watch?v=Yv_4RXyLjL8)
17 | - [FreeCodeCamp - JAVA programming for beginners](https://www.youtube.com/watch?v=A74TOX803D0)
18 | - [12 hours JAVA tutorial + JAVA Swing tutorial](https://www.youtube.com/watch?v=xk4_1vDrzzo)
19 |
20 | ### Video Playlists
21 | - [Bucky's beginner Java](https://www.youtube.com/playlist?list=PLFE2CE09D83EE3E28)
22 | - [Bucky's intermediate Java](https://www.youtube.com/playlist?list=PL27BCE863B6A864E3)
23 |
24 | ### На Русском
25 | - RU - Гоша Дударь - https://www.youtube.com/playlist?list=PL0lO_mIqDDFW2xXiWSfjT7hEdOUZHVNbK
26 | - RU https://www.youtube.com/playlist?list=PLlb7e2G7aSpRZSRZxANkvpYC82BXUzCTY
27 | - RU https://www.youtube.com/playlist?list=PLZqgWWF4O-zgDLDBMva788aJf_vQ9GKJv
28 |
29 | ### Books
30 | - Java How to Program, 10th edition
31 | - Java A Beginner’s Guide, 6th edition
32 | - Java for Dummies, 4th edition
33 |
--------------------------------------------------------------------------------
/lab-09-networking/Server.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Student: Rustam Zokirov
3 | * ID: U1910049
4 | * Lab #9: Networking, socket programming
5 | * Server side
6 | */
7 |
8 | // import libraries
9 | import java.io.*; // DataInputStream/DataOutputStream
10 | import java.net.*; // ServerSocket/Socket
11 | import java.util.*;
12 |
13 | public class Server {
14 |
15 | public static void main(String[] args) {
16 | new Server();
17 | }
18 |
19 | public Server() { // constructor
20 | try {
21 | // Create a server socket
22 | ServerSocket serverSocket = new ServerSocket(8000);
23 | System.out.println("Server started at " + new Date() + '\n');
24 |
25 | // Listen for a connection request
26 | Socket socket = serverSocket.accept();
27 |
28 | // Create data input and output streams
29 | DataInputStream inputFromClient = new DataInputStream(socket.getInputStream());
30 | DataOutputStream outputToClient = new DataOutputStream(socket.getOutputStream());
31 |
32 | while (true) {
33 | // Receive radius from the client
34 | String message = inputFromClient.readUTF();
35 |
36 | InetAddress ip = socket.getInetAddress();
37 | System.out.println("Host Name: " + ip.getHostName());
38 | System.out.println("IP Address: " + ip.getHostAddress());
39 | System.out.println("We have received message: " + message);
40 |
41 | // Convert to upper case
42 | String convertedMessage = message.toUpperCase();
43 |
44 | // Send message back to the client
45 | outputToClient.writeUTF(convertedMessage);
46 | }
47 | }
48 | catch(IOException ex) {
49 | System.err.println(ex);
50 | }
51 | }
52 | }
--------------------------------------------------------------------------------
/jdbc-tutorial/JdbcSelectTest_insert.java:
--------------------------------------------------------------------------------
1 | import java.sql.*; // Use 'Connection', 'Statement' and 'ResultSet' classes in java.sql package
2 |
3 | // JDK 1.7 and above
4 | public class JdbcSelectTest_insert { // Save as "JdbcSelectTest.java"
5 | public static void main(String[] args) {
6 | try (
7 | // Step 1: Allocate a database 'Connection' object
8 | Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/IUT_DB?autoReconnect=true&useSSL=false", "root", "1234");
9 | // MySQL: "jdbc:mysql://hostname:port/databaseName", "username", "password"
10 |
11 | // Step 2: Allocate a 'Statement' object in the Connection
12 | Statement stmt = conn.createStatement();) {
13 | // Step 3: Execute a SQL SELECT query, the query result
14 | // is returned in a 'ResultSet' object.
15 | int sid=999;
16 | String sname="Muhaamad";
17 |
18 | String strSelect = "insert into student values (" +sid+","+"'" +sname+"')";
19 |
20 | System.out.println("The SQL query is: " + strSelect); // Echo For debugging
21 | System.out.println();
22 |
23 | int count = stmt.executeUpdate(strSelect);
24 |
25 | // Step 4: Process the ResultSet by scrolling the cursor forward via next().
26 | // For each row, retrieve the contents of the cells with getXxx(columnName).
27 | conn.close();
28 | } catch(SQLException ex) {
29 | ex.printStackTrace();
30 | }
31 | // Step 5: Close the resources - Done automatically by try-with-resources
32 | }
33 | }
34 |
35 | // to delete record
36 | // String strSelect = "delete from student where studentid ="+ sid;
37 |
--------------------------------------------------------------------------------
/java-networking/Server.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.net.*;
3 | import java.util.*;
4 | import java.awt.*;
5 | import javax.swing.*;
6 |
7 | public class Server extends JFrame {
8 | // Text area for displaying contents
9 | private JTextArea jta = new JTextArea();
10 |
11 | public static void main(String[] args) {
12 | new Server();
13 | }
14 |
15 | public Server() {
16 | // Place text area on the frame
17 | setLayout(new BorderLayout());
18 | add(new JScrollPane(jta), BorderLayout.CENTER);
19 |
20 | setTitle("Server");
21 | setSize(500, 300);
22 | setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
23 | setVisible(true); // It is necessary to show the frame here!
24 |
25 | try {
26 | // Create a server socket
27 | ServerSocket serverSocket = new ServerSocket(8000);
28 | jta.append("Server started at " + new Date() + '\n');
29 |
30 | // Listen for a connection request
31 | Socket socket = serverSocket.accept();
32 |
33 | // Create data input and output streams
34 | DataInputStream inputFromClient = new DataInputStream(
35 | socket.getInputStream());
36 | DataOutputStream outputToClient = new DataOutputStream(
37 | socket.getOutputStream());
38 |
39 | while (true) {
40 | // Receive radius from the client
41 | double radius = inputFromClient.readDouble();
42 |
43 | // Compute area
44 | double area = radius * radius * Math.PI;
45 |
46 | // Send area back to the client
47 | outputToClient.writeDouble(area);
48 |
49 | jta.append("Radius received from client: " + radius + '\n');
50 | jta.append("Area found: " + area + '\n');
51 | }
52 | }
53 | catch(IOException ex) {
54 | System.err.println(ex);
55 | }
56 | }
57 | }
--------------------------------------------------------------------------------
/lab-09-networking/Client.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Student: Rustam Zokirov
3 | * ID: U1910049
4 | * Lab #9: Networking, socket programming
5 | * Client side
6 | */
7 |
8 | // import libraries we need
9 | import java.io.*; // DataInputStream/DataOutputStream
10 | import java.net.*; // ServerSocket/Socket
11 | import java.util.Scanner;
12 |
13 | public class Client {
14 | private DataOutputStream toServer;
15 | private DataInputStream fromServer;
16 |
17 | public static void main(String[] args) {
18 | new Client();
19 | }
20 |
21 | public Client() { // constructor
22 | try {
23 | // Create a socket to connect to the server
24 | Socket socket = new Socket("localhost", 8000);
25 |
26 | Scanner sc = new Scanner(System.in);
27 | String message;
28 |
29 | do {
30 | System.out.print("Please enter a message (0 = exit): ");
31 | message = sc.next();
32 |
33 | if (message.compareTo("0") == 0)
34 | break;
35 |
36 | // Create an input stream to receive data from the server
37 | fromServer = new DataInputStream(socket.getInputStream());
38 |
39 | // Create an output stream to send data to the server
40 | toServer = new DataOutputStream(socket.getOutputStream());
41 | toServer.writeUTF(message);
42 | toServer.flush();
43 |
44 | String convertedMessage = fromServer.readUTF();
45 |
46 | System.out.println("Converted message: " + convertedMessage);
47 | System.out.println();
48 |
49 | } while(true);
50 |
51 | }
52 | catch (IOException ex) {
53 | System.out.println(ex.toString() + '\n');
54 | }
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/midterm-exam/Account.java:
--------------------------------------------------------------------------------
1 | import java.util.Date;
2 |
3 | public class Account {
4 | private int id = 0;
5 | private double balance = 0.0;
6 | private double annualInterestRate = 0.0;
7 | private Date dateCreated;
8 |
9 |
10 | public Account() {}
11 |
12 | public Account(int id, int balance) {
13 | this.id = id;
14 | this.balance = balance;
15 | }
16 |
17 | public int getId() {
18 | return id;
19 | }
20 |
21 | public void setId(int id) {
22 | this.id = id;
23 | }
24 |
25 | public double getBalance() {
26 | return balance;
27 | }
28 |
29 | public void setBalance(double balance) {
30 | this.balance = balance;
31 | }
32 |
33 | public double getAnnualInterestRate() {
34 | return annualInterestRate;
35 | }
36 |
37 | public void setAnnualInterestRate(double annualInterestRate) {
38 | this.annualInterestRate = annualInterestRate;
39 | }
40 |
41 | public Date getDateCreated() {
42 | return dateCreated;
43 | }
44 |
45 | void withdraw(double amount) {
46 | balance -= amount;
47 | }
48 |
49 | void deposit(double amount) {
50 | balance += amount;
51 | }
52 |
53 | double getMonthlyInterestRate() {
54 | return annualInterestRate/12;
55 | }
56 |
57 | double getMonthlyInterest() {
58 | return (annualInterestRate/12)*balance;
59 | }
60 |
61 | }
62 |
63 | interface Visitor {
64 | double visit(Account account);
65 | }
66 |
67 | class TaxCalculator implements Visitor {
68 |
69 | @Override
70 | public double visit(Account account) {
71 | return null;
72 | }
73 | }
74 |
75 | class DailyInterestCalculator implements Visitor {
76 |
77 | @Override
78 | public double visit(Account account) {
79 | return null;
80 | }
81 | }
82 |
--------------------------------------------------------------------------------
/jdbc-tutorial/JDBCExample.java:
--------------------------------------------------------------------------------
1 | // information to run this program
2 | // to compile the program
3 | // javac JDBCExample.java
4 | // first method
5 | // to run the program
6 | // java -cp "C:\mysql-connector-java-5.1.49\mysql-connector-java-5.1.49-bin.jar;" JDBCExample
7 | // or
8 | // second method
9 | // set path
10 | // set path=%path%;C:\mysql-connector-java-5.1.49;
11 | // java JDBCExample
12 | // either your can use hostname 127.0.0.1 or localhost
13 |
14 | // default port number 3306
15 |
16 | import java.sql.Connection; // to establish a connection
17 | import java.sql.DriverManager;
18 | import java.sql.SQLException;
19 |
20 | public class JDBCExample {
21 |
22 | public static void main(String[] args) {
23 |
24 | // https://docs.oracle.com/javase/8/docs/api/java/sql/package-summary.html#package.description
25 | // auto java.sql.Driver discovery -- no longer need to load a java.sql.Driver class via Class.forName
26 |
27 | // register JDBC driver, optional since java 1.6
28 | /*try {
29 | Class.forName("com.mysql.jdbc.Driver");
30 | } catch (ClassNotFoundException e) {
31 | e.printStackTrace();
32 | }*/
33 |
34 | // auto close connection
35 | try (Connection conn = DriverManager.getConnection(
36 | "jdbc:mysql://127.0.0.1:3306/IUT_DB?autoReconnect=true&useSSL=false", "root", "1234")) {
37 |
38 | if (conn != null) {
39 | System.out.println("Connected to the database!");
40 | } else {
41 | System.out.println("Failed to make connection!");
42 | }
43 |
44 | } catch (SQLException e) {
45 | System.err.format("SQL State: %s\n%s", e.getSQLState(), e.getMessage());
46 | } catch (Exception e) {
47 | e.printStackTrace();
48 | }
49 |
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/jdbc-tutorial/JdbcSelectTest.java:
--------------------------------------------------------------------------------
1 | import java.sql.*; // Use 'Connection', 'Statement' and 'ResultSet' classes in java.sql package
2 |
3 | // JDK 1.7 and above
4 |
5 | public class JdbcSelectTest { // Save as "JdbcSelectTest.java"
6 | public static void main(String[] args) {
7 | try (
8 | // Step 1: Allocate a database 'Connection' object
9 | Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/IUT_DB?autoReconnect=true&useSSL=false", "root", "1234");
10 | // MySQL: "jdbc:mysql://hostname:port/databaseName", "username", "password"
11 |
12 | // Step 2: Allocate a 'Statement' object in the Connection
13 | Statement stmt = conn.createStatement();) {
14 | // Step 3: Execute a SQL SELECT query, the query result
15 | // is returned in a 'ResultSet' object.
16 | String strSelect = "select Student_name, studentID from student";
17 | System.out.println("The SQL query is: " + strSelect); // Echo For debugging
18 | System.out.println();
19 |
20 | ResultSet rset = stmt.executeQuery(strSelect);
21 |
22 | // Step 4: Process the ResultSet by scrolling the cursor forward via next().
23 | // For each row, retrieve the contents of the cells with getXxx(columnName).
24 | System.out.println("The records selected are:");
25 | int rowCount = 0;
26 |
27 | while(rset.next()) { // Move the cursor to the next row, return false if no more row
28 | String sname = rset.getString("student_name");
29 | int sid= rset.getInt("studentID");
30 |
31 | System.out.println(sid+ " " +sname );
32 | ++rowCount;
33 | }
34 | System.out.println("Total number of records = " + rowCount);
35 |
36 | } catch(SQLException ex) {
37 | ex.printStackTrace();
38 | }
39 | // Step 5: Close the resources - Done automatically by try-with-resources
40 | }
41 | }
--------------------------------------------------------------------------------
/javafx-tutorial/JavaFXLayoutDemo.java:
--------------------------------------------------------------------------------
1 | /*import javafx.application.Application;
2 | import javafx.scene.Group;
3 | import javafx.scene.Scene;
4 | import javafx.scene.paint.Color;
5 | import javafx.scene.shape.Rectangle;
6 | import javafx.stage.Stage;
7 |
8 | public class JavaFXLayoutDemo extends Application {
9 |
10 | @Override
11 | public void start(Stage stage) {
12 | Group root = new Group();
13 | Scene scene = new Scene(root, 500, 500, Color.BLACK);
14 |
15 | Rectangle r = new Rectangle(25,25,250,250);
16 | r.setFill(Color.BLUE);
17 | root.getChildren().add(r);
18 |
19 | stage.setTitle("JavaFX Scene Graph Demo");
20 | stage.setScene(scene);
21 | stage.show();
22 | }
23 |
24 | public static void main(String[] args) {
25 | launch(args);
26 | }
27 | }*/
28 |
29 |
30 | import javafx.application.Application;
31 | import javafx.scene.Group;
32 | import javafx.scene.Scene;
33 | import javafx.scene.paint.Color;
34 | import javafx.scene.shape.Rectangle;
35 | import javafx.stage.Stage;
36 | import javafx.scene.control.Label;
37 | import javafx.scene.control.Button;
38 | import javafx.scene.control.TextField;
39 | import javafx.scene.layout.HBox;
40 | import javafx.scene.layout.VBox;
41 |
42 | public class JavaFXLayoutDemo extends Application {
43 |
44 | @Override
45 | public void start(Stage stage) {
46 |
47 | Label lblName = new Label("What is your Name ?");
48 | TextField tfName = new TextField("Type your name ");
49 | Button btOk = new Button("Ok");
50 |
51 | HBox group = new HBox();
52 |
53 | group.getChildren().add(lblName);
54 | group.getChildren().add(tfName);
55 | group.getChildren().add(btOk);
56 |
57 | Scene scene = new Scene(group,500, 500);
58 |
59 | stage.setTitle("JavaFX Scene Graph Demo");
60 | stage.setScene(scene);
61 | stage.show();
62 | }
63 |
64 | public static void main(String[] args) {
65 | launch(args);
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/template-menus/TemplateMenu2.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner; // Import the Scanner class
2 |
3 | public class TemplateMenu2 {
4 | public static void main(String[] args) {
5 |
6 | Scanner input = new Scanner(System.in); // Create a Scanner object
7 | int option, isExit; // Initializing some variables
8 |
9 | do { // Loop for reusing the program
10 | option = showMenu(); // The option value
11 |
12 | switch (option){
13 | case 1:
14 | System.out.println("***** DISPLAY *****");
15 |
16 | break;
17 |
18 | case 2:
19 | System.out.println("***** INSERT RECORD *****");
20 |
21 | break;
22 |
23 | case 3:
24 | System.out.println("***** UPDATE RECORD *****");
25 |
26 | break;
27 |
28 | case 4:
29 | System.out.println("***** DELETE RECORD *****");
30 |
31 | break;
32 |
33 | case 0:
34 | System.out.println("Quitting Program...");
35 | System.exit(0); // program ends
36 | break;
37 | default:
38 | System.out.println("Please choose a valid option!");
39 |
40 | } // End of switch
41 |
42 | System.out.print("\nDo you want to continue? (0.No 1.Yes) - ");
43 | isExit = input.nextInt(); // validation checking
44 |
45 | } while(isExit == 1);
46 |
47 | } // end of main()
48 |
49 | public static int showMenu() {
50 | Scanner input = new Scanner(System.in); // Create a Scanner object
51 |
52 | int option = 0;
53 | // Printing menu to screen
54 | System.out.println("\n***** MAIN MENU *****");
55 | System.out.println("1. Display records");
56 | System.out.println("2. Insert record");
57 | System.out.println("3. Update record");
58 | System.out.println("4. Delete record");
59 | System.out.println("0. Exit");
60 |
61 | // Getting user option from above menu
62 | System.out.print("Your choice: ");
63 | option = input.nextInt();
64 | System.out.println();
65 |
66 | return option;
67 | } // End of showMenu
68 | }
69 |
--------------------------------------------------------------------------------
/java-multithreading/Client.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.net.*;
3 | import java.awt.*;
4 | import java.awt.event.*;
5 | import javax.swing.*;
6 |
7 | public class Client extends JFrame {
8 | // Text field for receiving radius
9 | private JTextField jtf = new JTextField();
10 |
11 | // Text area to display contents
12 | private JTextArea jta = new JTextArea();
13 |
14 | // IO streams
15 | private DataOutputStream toServer;
16 | private DataInputStream fromServer;
17 |
18 | public static void main(String[] args) {
19 | new Client();
20 | }
21 |
22 | public Client() {
23 | // Panel p to hold the label and text field
24 | JPanel p = new JPanel();
25 | p.setLayout(new BorderLayout());
26 | p.add(new JLabel("Enter radius"), BorderLayout.WEST);
27 | p.add(jtf, BorderLayout.CENTER);
28 | jtf.setHorizontalAlignment(JTextField.RIGHT);
29 |
30 | setLayout(new BorderLayout());
31 | add(p, BorderLayout.NORTH);
32 | add(new JScrollPane(jta), BorderLayout.CENTER);
33 |
34 | jtf.addActionListener(new ButtonListener()); // Register listener
35 |
36 | setTitle("Client");
37 | setSize(500, 300);
38 | setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
39 | setVisible(true); // It is necessary to show the frame here!
40 |
41 | try {
42 | // Create a socket to connect to the server
43 | Socket socket = new Socket("localhost", 8000);
44 | // Socket socket = new Socket("130.254.204.36", 8000);
45 | // Socket socket = new Socket("drake.Armstrong.edu", 8000);
46 |
47 | // Create an input stream to receive data from the server
48 | fromServer = new DataInputStream(
49 | socket.getInputStream());
50 |
51 | // Create an output stream to send data to the server
52 | toServer =
53 | new DataOutputStream(socket.getOutputStream());
54 | }
55 | catch (IOException ex) {
56 | jta.append(ex.toString() + '\n');
57 | }
58 | }
59 |
60 | private class ButtonListener implements ActionListener {
61 | public void actionPerformed(ActionEvent e) {
62 | try {
63 | // Get the radius from the text field
64 | double radius = Double.parseDouble(jtf.getText().trim());
65 |
66 | // Send the radius to the server
67 | toServer.writeDouble(radius);
68 | toServer.flush();
69 |
70 | // Get area from the server
71 | double area = fromServer.readDouble();
72 |
73 | // Display to the text area
74 | jta.append("Radius is " + radius + "\n");
75 | jta.append("Area received from the server is "
76 | + area + '\n');
77 | }
78 | catch (IOException ex) {
79 | System.err.println(ex);
80 | }
81 | }
82 | }
83 | }
--------------------------------------------------------------------------------
/java-networking/Client.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.net.*;
3 | import java.awt.*;
4 | import java.awt.event.*;
5 | import javax.swing.*;
6 |
7 | public class Client extends JFrame {
8 | // Text field for receiving radius
9 | private JTextField jtf = new JTextField();
10 |
11 | // Text area to display contents
12 | private JTextArea jta = new JTextArea();
13 |
14 | // IO streams
15 | private DataOutputStream toServer;
16 | private DataInputStream fromServer;
17 |
18 | public static void main(String[] args) {
19 | new Client();
20 | }
21 |
22 | public Client() {
23 | // Panel p to hold the label and text field
24 | JPanel p = new JPanel();
25 | p.setLayout(new BorderLayout());
26 | p.add(new JLabel("Enter radius"), BorderLayout.WEST);
27 | p.add(jtf, BorderLayout.CENTER);
28 | jtf.setHorizontalAlignment(JTextField.RIGHT);
29 |
30 | setLayout(new BorderLayout());
31 | add(p, BorderLayout.NORTH);
32 | add(new JScrollPane(jta), BorderLayout.CENTER);
33 |
34 | jtf.addActionListener(new ButtonListener()); // Register listener
35 |
36 | setTitle("Client");
37 | setSize(500, 300);
38 | setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
39 | setVisible(true); // It is necessary to show the frame here!
40 |
41 | try {
42 | // Create a socket to connect to the server
43 | Socket socket = new Socket("localhost", 8000);
44 | // Socket socket = new Socket("130.254.204.36", 8000);
45 | // Socket socket = new Socket("drake.Armstrong.edu", 8000);
46 |
47 | // Create an input stream to receive data from the server
48 | fromServer = new DataInputStream(
49 | socket.getInputStream());
50 |
51 | // Create an output stream to send data to the server
52 | toServer =
53 | new DataOutputStream(socket.getOutputStream());
54 | }
55 | catch (IOException ex) {
56 | jta.append(ex.toString() + '\n');
57 | }
58 | }
59 |
60 | private class ButtonListener implements ActionListener {
61 | public void actionPerformed(ActionEvent e) {
62 | try {
63 | // Get the radius from the text field
64 | double radius = Double.parseDouble(jtf.getText().trim());
65 |
66 | // Send the radius to the server
67 | toServer.writeDouble(radius);
68 | toServer.flush();
69 |
70 | // Get area from the server
71 | double area = fromServer.readDouble();
72 |
73 | // Display to the text area
74 | jta.append("Radius is " + radius + "\n");
75 | jta.append("Area received from the server is "
76 | + area + '\n');
77 | }
78 | catch (IOException ex) {
79 | System.err.println(ex);
80 | }
81 | }
82 | }
83 | }
--------------------------------------------------------------------------------
/javafx-tutorial/EventFiltersExample.java:
--------------------------------------------------------------------------------
1 | import javafx.application.Application;
2 | import static javafx.application.Application.launch;
3 | import javafx.event.EventHandler;
4 |
5 | import javafx.scene.Group;
6 | import javafx.scene.Scene;
7 | import javafx.scene.input.MouseEvent;
8 | import javafx.scene.paint.Color;
9 | import javafx.scene.shape.Circle;
10 |
11 | import javafx.scene.text.Font;
12 | import javafx.scene.text.FontWeight;
13 | import javafx.scene.text.Text;
14 | import javafx.stage.Stage;
15 |
16 | public class EventFiltersExample extends Application {
17 | @Override
18 | public void start(Stage stage) {
19 | //Drawing a Circle
20 | Circle circle = new Circle();
21 |
22 | //Setting the position of the circle
23 | circle.setCenterX(300.0f);
24 | circle.setCenterY(135.0f);
25 |
26 | //Setting the radius of the circle
27 | circle.setRadius(25.0f);
28 |
29 | //Setting the color of the circle
30 | circle.setFill(Color.BROWN);
31 |
32 | //Setting the stroke width of the circle
33 | circle.setStrokeWidth(20);
34 |
35 | //Setting the text
36 | Text text = new Text("Click on the circle to change its color");
37 |
38 | //Setting the font of the text
39 | text.setFont(Font.font(null, FontWeight.BOLD, 15));
40 |
41 | //Setting the color of the text
42 | text.setFill(Color.CRIMSON);
43 |
44 | //setting the position of the text
45 | text.setX(150);
46 | text.setY(50);
47 |
48 | //Creating the mouse event handler
49 | EventHandler eventHandler = new EventHandler() {
50 | @Override
51 | public void handle(MouseEvent e) {
52 | System.out.println("Hello World");
53 | circle.setFill(Color.DARKSLATEBLUE);
54 | }
55 | };
56 | //Registering the event filter
57 | circle.addEventFilter(MouseEvent.MOUSE_CLICKED, eventHandler);
58 |
59 | //Creating a Group object
60 | Group root = new Group(circle, text);
61 |
62 | //Creating a scene object
63 | Scene scene = new Scene(root, 600, 300);
64 |
65 | //Setting the fill color to the scene
66 | scene.setFill(Color.LAVENDER);
67 |
68 | //Setting title to the Stage
69 | stage.setTitle("Event Filters Example");
70 |
71 | //Adding scene to the stage
72 | stage.setScene(scene);
73 |
74 | //Displaying the contents of the stage
75 | stage.show();
76 | }
77 | public static void main(String args[]){
78 | launch(args);
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/java-multithreading/MultiThreadServerAB.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.net.*;
3 | import java.util.*;
4 |
5 |
6 | public class MultiThreadServerAB
7 | {
8 |
9 |
10 | public static void main(String[] args) {
11 | new MultiThreadServerAB();
12 | }
13 |
14 | public MultiThreadServerAB() {
15 |
16 |
17 |
18 | try {
19 | // Create a server socket
20 | ServerSocket serverSocket = new ServerSocket(8000);
21 | System.out.println("MultiThreadServer started at " + new Date() + '\n');
22 |
23 | // Number a client
24 | int clientNo = 1;
25 |
26 | while (true) {
27 | // Listen for a new connection request
28 | Socket socket = serverSocket.accept();
29 |
30 | // Display the client number
31 | System.out.println("Starting thread for client " + clientNo +
32 | " at " + new Date() + '\n');
33 |
34 | // Find the client's host name, and IP address
35 | InetAddress inetAddress = socket.getInetAddress();
36 | System.out.println("Client " + clientNo + "'s host name is "
37 | + inetAddress.getHostName() + "\n");
38 | System.out.println("Client " + clientNo + "'s IP Address is "
39 | + inetAddress.getHostAddress() + "\n");
40 |
41 | // Create a new thread for the connection
42 | HandleAClient task = new HandleAClient(socket);
43 | Thread t1 = new Thread(task);
44 | // Start the new thread
45 | t1.start();
46 |
47 | // Increment clientNo
48 | clientNo++;
49 | }
50 | }
51 | catch(IOException ex) {
52 | System.err.println(ex);
53 | }
54 | }
55 |
56 | // Inner class
57 | // Define the thread class for handling new connection
58 | class HandleAClient implements Runnable {
59 | private Socket socket; // A connected socket
60 |
61 | /** Construct a thread */
62 | public HandleAClient(Socket socket) {
63 | this.socket = socket;
64 | }
65 |
66 | /** Run a thread */
67 | public void run() {
68 | try {
69 | // Create data input and output streams
70 | DataInputStream inputFromClient = new DataInputStream(
71 | socket.getInputStream());
72 | DataOutputStream outputToClient = new DataOutputStream(
73 | socket.getOutputStream());
74 |
75 | // Continuously serve the client
76 | while (true) {
77 | // Receive radius from the client
78 | double radius = inputFromClient.readDouble();
79 |
80 | // Compute area
81 | double area = radius * radius * Math.PI;
82 |
83 | // Send area back to the client
84 | outputToClient.writeDouble(area);
85 |
86 | System.out.println("radius received from client: " +
87 | radius + '\n');
88 | System.out.println("Area found: " + area + '\n');
89 | }
90 | }
91 | catch(IOException e) {
92 | System.err.println(e);
93 | }
94 | }
95 | }
96 | }
--------------------------------------------------------------------------------
/lab-02/App_2.0.java:
--------------------------------------------------------------------------------
1 | /* Student: Rustam Zokirov
2 | ID: U1910049
3 | Lab: #2 BMI Calculator
4 | */
5 | import java.util.Scanner; // Import the Scanner class
6 |
7 | public class App2 { // Create a Class App
8 | public static void calculate(int choice){
9 | boolean isCalculate = true;
10 | float height = 0, weight = 0, BMI; // declaring some variables
11 | int choice2;
12 |
13 | while(isCalculate) {
14 | Scanner input = new Scanner(System.in); // Create a scanner object
15 |
16 | for (int i = 0; i == 0; ) { //taking data from user and check for validation
17 | System.out.println("Enter height: ");
18 | height = input.nextFloat(); // read height input
19 | System.out.println("Enter weight: ");
20 | weight = input.nextFloat(); // read weight input
21 |
22 | if (height > 0 && weight > 0) // validate for >0
23 | i = 1;
24 | else
25 | System.out.println("Enter correct values!");
26 | }
27 |
28 | if (choice == 1) { // for kg
29 | BMI = weight / (height * height);
30 | }
31 | else { // for pounds
32 | BMI = 703 * weight / (height * height);
33 | }
34 |
35 | if (BMI < 18.5)
36 | System.out.printf("BMI: %.2f Underweight", BMI);
37 | else if (BMI >= 18.5 && BMI < 25)
38 | System.out.printf("BMI: %.2f Normal", BMI);
39 | else if (BMI >= 25 && BMI < 30)
40 | System.out.printf("BMI: %.2f Overweight", BMI);
41 | else if (BMI >= 30 && BMI < 35)
42 | System.out.printf("BMI: %.2f Obese", BMI);
43 | else
44 | System.out.printf("BMI: %.2f Extremely Obese", BMI);
45 |
46 | System.out.println("\nDo you want to calculate again? (1. YES / Any key. NO) ");
47 | choice2 = input.nextInt(); // read the input
48 |
49 | if (choice2 != 1)
50 | isCalculate = false; // exit from the loop
51 | }
52 |
53 | }
54 |
55 | public static void main(String[] args){
56 | Scanner input = new Scanner(System.in); // Create a scanner object
57 | int choice;
58 |
59 | System.out.println("*** Welcome to BMI Calculator! ***");
60 | System.out.println("Please enter only numbers!\n" + "1. Kilograms and meters\n" + "2. Pounds and inches\n" + "0. Exit\n" + "Choose option: ");
61 | choice = input.nextInt();
62 |
63 | switch (choice) { // switch for the menu
64 | case 0: { // Pounds and inches
65 | System.exit(0); //
66 | }break;
67 | case 1: { // Kilograms and meters
68 | calculate(1);
69 | }break;
70 | case 2: { // Pounds and inches
71 | calculate(2);
72 | }break;
73 | default:{
74 | System.out.println("Invalid input!");
75 | }break;
76 | } // switch
77 | } // main()
78 | } // Class App
79 |
--------------------------------------------------------------------------------
/java-networking/URLDemo.java:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | The Java URL class represents an URL.
4 | URL is an acronym for Uniform Resource Locator.
5 | It points to a resource on the World Wide Web.
6 |
7 | A URL contains many information:
8 |
9 | Protocol:
10 | Server name or IP Address:
11 | Port Number: It is an optional attribute.
12 | File Name or directory name:
13 |
14 |
15 | Constructors of Java URL class
16 | URL(String spec)
17 |
18 |
19 | Creates an instance of a URL from the String representation.
20 |
21 | URL(String protocol, String host, int port, String file)
22 |
23 | Creates an instance of a URL from the given protocol, host, port number, and file.
24 |
25 | URL(String protocol, String host, int port, String file, URLStreamHandler handler)
26 |
27 | Creates an instance of a URL from the given protocol, host, port number, file, and handler.
28 |
29 | URL(String protocol, String host, String file)
30 |
31 | Creates an instance of a URL from the given protocol name, host name, and file name.
32 |
33 | URL(URL context, String spec)
34 |
35 | Creates an instance of a URL by parsing the given spec within a specified context.
36 |
37 | URL(URL context, String spec, URLStreamHandler handler)
38 |
39 | Creates an instance of a URL by parsing the given spec with the specified handler within a given context.
40 |
41 | Method Description
42 | public String getProtocol() it returns the protocol of the URL.
43 | public String getHost() it returns the host name of the URL.
44 | public String getPort() it returns the Port Number of the URL.
45 | public String getFile() it returns the file name of the URL.
46 | public String getAuthority() it returns the authority of the URL.
47 | public String toString() it returns the string representation of the URL.
48 | public String getQuery() it returns the query string of the URL.
49 | public String getDefaultPort() it returns the default port of the URL.
50 | public URLConnection openConnection() it returns the instance of URLConnection i.e. associated with this URL.
51 | public boolean equals(Object obj) it compares the URL with the given object.
52 | public Object getContent() it returns the content of the URL.
53 | public String getRef() it returns the anchor or reference of the URL.
54 | public URI toURI() it returns a URI of the URL.
55 |
56 | */
57 |
58 | //URLDemo.java
59 | import java.net.*;
60 | public class URLDemo {
61 | public static void main(String[] args) {
62 | try{
63 | URL url=new URL("https://www.google.com/search?q=javatpoint&oq=javatpoint&sourceid=chrome&ie=UTF-8");
64 |
65 | System.out.println("Protocol: "+url.getProtocol());
66 | System.out.println("Host Name: "+url.getHost());
67 | System.out.println("Port Number: "+url.getPort());
68 | System.out.println("Default Port Number: "+url.getDefaultPort());
69 | System.out.println("Query String: "+url.getQuery());
70 | System.out.println("Path: "+url.getPath());
71 | System.out.println("File: "+url.getFile());
72 |
73 | }
74 | catch(Exception e) {
75 | System.out.println(e);
76 | }
77 | }
78 | }
--------------------------------------------------------------------------------
/midterm-exam/BankAccount.java:
--------------------------------------------------------------------------------
1 | import java.util.Date;
2 |
3 | public class Account {
4 | private int id;
5 | private double balance;
6 | private double annualInterestRate;
7 | private Date dateCreated;
8 |
9 | public Account() {
10 | this.id = 0;
11 | this.balance = 0;
12 | this.annualInterestRate = 1.2;
13 | this.dateCreated = new Date();
14 | }
15 |
16 | public Account(int id, double balance) {
17 | this.id = id;
18 | this.balance = balance;
19 | this.annualInterestRate = 1.2;
20 | this.dateCreated = new Date();
21 | }
22 |
23 | public int getId() {
24 | return this.id;
25 | }
26 |
27 | public void setId(int id) {
28 | this.id = id;
29 | }
30 |
31 | public double getBalance() {
32 | return this.balance;
33 | }
34 |
35 | public void setBalance(double balance) {
36 | this.balance = balance;
37 | }
38 |
39 | public double getAnnualInterestRate() {
40 | return this.annualInterestRate;
41 | }
42 |
43 | public void setAnnualInterestRate(double annualInterestRate) {
44 | this.annualInterestRate = annualInterestRate;
45 | }
46 |
47 | public Date getDateCreated() {
48 | return this.dateCreated;
49 | }
50 |
51 | public void withdraw(double amount){
52 | if (amount<=0) {
53 | throw new RuntimeException("Invalid amount.");
54 | }
55 | if (amount<=this.balance) {
56 | this.setBalance(this.balance-amount);
57 | } else {
58 | throw new RuntimeException("Not enough funds");
59 | }
60 | }
61 |
62 | public void deposit(double amount){
63 | if (amount<=0) {
64 | throw new RuntimeException("Invalid amount.");
65 | }
66 | this.setBalance(this.balance+amount);
67 | }
68 |
69 | public double getMonthlyInterestRate(){
70 | return this.annualInterestRate / 12;
71 | }
72 |
73 | public double getMonthlyInterest(){
74 | return (this.annualInterestRate / 12) * this.balance;
75 | }
76 |
77 | public double accept(Visitor visitor){
78 | return visitor.visit(this);
79 | }
80 | }
81 |
82 |
83 | public interface Visitor {
84 | double visit(Account account);
85 | }
86 |
87 | public class TaxCalculator implements Visitor {
88 | @Override
89 | public double visit(Account account) {
90 | return 0.05 * account.getAnnualInterestRate() * account.getBalance();
91 | }
92 | }
93 |
94 | public class DailyInterestCalculator implements Visitor {
95 | @Override
96 | public double visit(Account account) {
97 | return (account.getMonthlyInterestRate() / 30) * account.getBalance();
98 | }
99 | }
100 |
101 | // Problem 3 optional part
102 | public class AccountTest {
103 | public static void main(String[] args) {
104 | Visitor v1 = new TaxCalculator();
105 |
106 | Account account = new Account(123, 100);
107 |
108 | double tax = account.accept(v1);
109 | System.out.printf("Annual tax: %.2f$%n", tax);
110 |
111 | v1 = new DailyInterestCalculator();
112 | double dailyInterest = account.accept(v1);
113 |
114 | System.out.printf("Daily interest: %.2f$%n", dailyInterest);
115 | }
116 | }
117 |
--------------------------------------------------------------------------------
/java-multithreading/MultiThreadServer.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.net.*;
3 | import java.util.*;
4 | import java.awt.*;
5 | import javax.swing.*;
6 |
7 | public class MultiThreadServer extends JFrame {
8 | // Text area for displaying contents
9 | private JTextArea jta = new JTextArea();
10 |
11 | public static void main(String[] args) {
12 | new MultiThreadServer();
13 | }
14 |
15 | public MultiThreadServer() {
16 | // Place text area on the frame
17 | setLayout(new BorderLayout());
18 | add(new JScrollPane(jta), BorderLayout.CENTER);
19 |
20 | setTitle("MultiThreadServer");
21 | setSize(500, 300);
22 | setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
23 | setVisible(true); // It is necessary to show the frame here!
24 |
25 | try {
26 | // Create a server socket
27 | ServerSocket serverSocket = new ServerSocket(8000);
28 | jta.append("MultiThreadServer started at " + new Date() + '\n');
29 |
30 | // Number a client
31 | int clientNo = 1;
32 |
33 | while (true) {
34 | // Listen for a new connection request
35 | Socket socket = serverSocket.accept();
36 |
37 | // Display the client number
38 | jta.append("Starting thread for client " + clientNo +
39 | " at " + new Date() + '\n');
40 |
41 | // Find the client's host name, and IP address
42 | InetAddress inetAddress = socket.getInetAddress();
43 | jta.append("Client " + clientNo + "'s host name is "
44 | + inetAddress.getHostName() + "\n");
45 | jta.append("Client " + clientNo + "'s IP Address is "
46 | + inetAddress.getHostAddress() + "\n");
47 |
48 | // Create a new thread for the connection
49 | HandleAClient task = new HandleAClient(socket);
50 |
51 | // Start the new thread
52 | new Thread(task).start();
53 |
54 | // Increment clientNo
55 | clientNo++;
56 | }
57 | }
58 | catch(IOException ex) {
59 | System.err.println(ex);
60 | }
61 | }
62 |
63 | // Inner class
64 | // Define the thread class for handling new connection
65 | class HandleAClient implements Runnable {
66 | private Socket socket; // A connected socket
67 |
68 | /** Construct a thread */
69 | public HandleAClient(Socket socket) {
70 | this.socket = socket;
71 | }
72 |
73 | /** Run a thread */
74 | public void run() {
75 | try {
76 | // Create data input and output streams
77 | DataInputStream inputFromClient = new DataInputStream(
78 | socket.getInputStream());
79 | DataOutputStream outputToClient = new DataOutputStream(
80 | socket.getOutputStream());
81 |
82 | // Continuously serve the client
83 | while (true) {
84 | // Receive radius from the client
85 | double radius = inputFromClient.readDouble();
86 |
87 | // Compute area
88 | double area = radius * radius * Math.PI;
89 |
90 | // Send area back to the client
91 | outputToClient.writeDouble(area);
92 |
93 | jta.append("radius received from client: " +
94 | radius + '\n');
95 | jta.append("Area found: " + area + '\n');
96 | }
97 | }
98 | catch(IOException e) {
99 | System.err.println(e);
100 | }
101 | }
102 | }
103 | }
--------------------------------------------------------------------------------
/java-swing-tutorial/ShowGridBagLayout.java:
--------------------------------------------------------------------------------
1 | package programs;
2 |
3 | import java.awt.*;
4 | import javax.swing.*;
5 |
6 | public class ShowGridBagLayout extends JApplet {
7 | private JLabel jlbl = new JLabel(
8 | "Resize the Window and Study GridBagLayout", JLabel.CENTER);
9 | private JTextArea jta1 = new JTextArea("Text Area 1", 5, 15 );
10 | private JTextArea jta2 = new JTextArea("Text Area 2", 5, 15 );
11 | private JTextField jtf = new JTextField("JTextField");
12 | private JPanel jp = new JPanel();
13 | private JButton jbt1 = new JButton("Button 1");
14 | private JButton jbt2 = new JButton("Button 2");
15 |
16 | public ShowGridBagLayout() {
17 | // Set GridBagLayout in the container
18 | setLayout(new GridBagLayout());
19 |
20 | // Create an GridBagConstraints object
21 | GridBagConstraints gbConstraints = new GridBagConstraints();
22 |
23 | gbConstraints.fill = GridBagConstraints.BOTH;
24 | gbConstraints.anchor = GridBagConstraints.CENTER;
25 |
26 | Container container = getContentPane();
27 |
28 | // Place JLabel to occupy row 0 (the first row)
29 | addComp(jlbl, container, gbConstraints, 0, 0, 1, 4, 0, 0);
30 |
31 | // Place text area 1 in row 1 and 2, and column 0
32 | addComp(jta1, container, gbConstraints, 1, 0, 2, 1, 5, 1);
33 |
34 | // Place text area 2 in row 1 and column 3
35 | addComp(jta2, container, gbConstraints, 1, 3, 1, 1, 5, 1);
36 |
37 | // Place text field in row 2 and column 3
38 | addComp(jtf, container, gbConstraints, 2, 3, 1, 1, 5, 0);
39 |
40 | // Place JButton 1 in row 3 and column 1
41 | addComp(jbt1, container, gbConstraints, 3, 1, 1, 1, 5, 0);
42 |
43 | // Place JButton 2 in row 3 and column 2
44 | addComp(jbt2, container, gbConstraints, 3, 2, 1, 1, 5, 0);
45 |
46 | // Place Panel in row 1 and 2, and column 1 and 2
47 | jp.setBackground(Color.red);
48 | jp.setBorder(new javax.swing.border.LineBorder(Color.black));
49 | gbConstraints.insets = new Insets(10, 10, 10, 10);
50 | addComp(jp, container, gbConstraints, 1, 1, 2, 2, 10, 1);
51 | }
52 |
53 | /** Add a component to the container of GridBagLayout */
54 | private void addComp(Component c, Container container,
55 | GridBagConstraints gbConstraints,
56 | int row, int column,
57 | int numberOfRows, int numberOfColumns,
58 | double weightx, double weighty) {
59 | // Set parameters
60 | gbConstraints.gridx = column;
61 | gbConstraints.gridy = row;
62 | gbConstraints.gridwidth = numberOfColumns;
63 | gbConstraints.gridheight = numberOfRows;
64 | gbConstraints.weightx = weightx;
65 | gbConstraints.weighty = weighty;
66 |
67 | // Add component to the container with the specified layout
68 | container.add(c, gbConstraints);
69 | }
70 |
71 | public static void main(String[] args) {
72 | ShowGridBagLayout applet = new ShowGridBagLayout();
73 | JFrame frame = new JFrame();
74 | //EXIT_ON_CLOSE == 3
75 | frame.setDefaultCloseOperation(3);
76 | frame.setTitle("ShowGridBagLayout");
77 | frame.getContentPane().add(applet, BorderLayout.CENTER);
78 | applet.init();
79 | applet.start();
80 | frame.setSize(400,320);
81 | Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
82 | frame.setLocation((d.width - frame.getSize().width) / 2,
83 | (d.height - frame.getSize().height) / 2);
84 | frame.setVisible(true);
85 | }
86 | }
--------------------------------------------------------------------------------
/lab-06-swing/Printer.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Rustam Zokirov, U1910049
3 | * Working with Layouts
4 | */
5 | import javax.swing.*; // import library to work with GUI
6 |
7 | public class Printer extends JFrame { // inherit JFrame
8 | public static void main(String[] args) {
9 | // Labels
10 | JLabel jlblPrinter = new JLabel("Printer: My Printer");
11 | jlblPrinter.setBounds(30, 10, 150, 20); // set the coordinates, length and width
12 | JLabel jlblQuality = new JLabel("Print Quality:");
13 | jlblQuality.setBounds(30, 100, 150, 20); // set the coordinates, length and width
14 |
15 | // Text areas
16 | JTextArea jtxtFirst = new JTextArea();
17 | jtxtFirst.setBounds(25, 35, 50, 60);
18 | JTextArea jtxtSecond = new JTextArea();
19 | jtxtSecond.setBounds(150, 35, 40, 60);
20 | JTextArea jtxtThird = new JTextArea();
21 | jtxtThird.setBounds(270, 35, 50, 60);
22 |
23 | // Check box
24 | JCheckBox checkBox1 = new JCheckBox("Image", true);
25 | checkBox1.setBounds(75, 37, 60, 15);
26 | JCheckBox checkBox2 = new JCheckBox("Text");
27 | checkBox2.setBounds(75, 57, 60, 15);
28 | JCheckBox checkBox3 = new JCheckBox("Code");
29 | checkBox3.setBounds(75, 77, 60, 15);
30 | JCheckBox printFileBox = new JCheckBox("Print to file");
31 | printFileBox.setBounds(195, 100, 120, 20);
32 |
33 | // Radio Buttons
34 | JRadioButton radioButton1 = new JRadioButton("Selection");
35 | radioButton1.setBounds(190, 37, 80, 15);
36 | JRadioButton radioButton2 = new JRadioButton("All", true);
37 | radioButton2.setBounds(190, 57, 80, 15);
38 | JRadioButton radioButton3 = new JRadioButton("Applet");
39 | radioButton3.setBounds(190, 77, 80, 15);
40 |
41 | // ComboBox
42 | String quality[] = {"High","Medium","Low"}; // array which contatins all the choices
43 | JComboBox comboBox = new JComboBox(quality);
44 | comboBox.setBounds(115, 100, 70, 20);
45 |
46 | // Buttons
47 | JButton jbtOkButton = new JButton("Ok");
48 | jbtOkButton.setBounds(330, 20, 75, 25);
49 | JButton jbtCancelButton = new JButton("Cancel");
50 | jbtCancelButton.setBounds(330, 50, 75, 25);
51 | JButton jbtSetupButton = new JButton("Setup");
52 | jbtSetupButton.setBounds(330, 80, 75, 25);
53 | JButton jbtHelpButton = new JButton("Help");
54 | jbtHelpButton.setBounds(330, 110, 75, 25);
55 |
56 | // Create Frame
57 | JFrame frame = new Printer();
58 | frame.add(jlblPrinter);
59 | frame.add(jlblQuality);
60 |
61 | frame.add(jtxtFirst);
62 | frame.add(jtxtSecond);
63 | frame.add(jtxtThird);
64 |
65 | frame.add(checkBox1);
66 | frame.add(checkBox2);
67 | frame.add(checkBox3);
68 | frame.add(printFileBox);
69 |
70 | frame.add(radioButton1);
71 | frame.add(radioButton2);
72 | frame.add(radioButton3);
73 |
74 | frame.add(comboBox);
75 |
76 | frame.add(jbtOkButton);
77 | frame.add(jbtCancelButton);
78 | frame.add(jbtSetupButton);
79 | frame.add(jbtHelpButton);
80 |
81 | // Some settings
82 | frame.setTitle("Printer");
83 | frame.setLayout(null);
84 | frame.setSize(450, 200);
85 | frame.setLocation(200, 100);
86 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
87 | frame.setVisible(true);
88 | }
89 | }
90 |
--------------------------------------------------------------------------------
/java-swing-tutorial/java-swing.md:
--------------------------------------------------------------------------------
1 | ## Java Swing
2 | ### GUI Basics
3 | - [Lecture Notes](lecture-notes/GUI_Basics.ppt)
4 |
5 | - [Swing Notes](lecture-notes/Creating_User_Interfaces_Swing.ppt)
6 |
7 | - Swing (interface) vs. AWT (event handling)
8 |
9 | - ```java
10 | import javax.swing.*;
11 |
12 | public class MyFrame {
13 | public static void main(String[] args) {
14 | JFrame frame = new JFrame("Test Frame");
15 | frame.setSize(400, 300);
16 | frame.setLocationRelativeTo(null);
17 | frame.setVisible(true);
18 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
19 | }
20 | }
21 | ```
22 |
23 | - ```java
24 | import javax.swing.*;
25 |
26 | public class MyFrameWithComponents {
27 | public static void main(String[] args) {
28 | JFrame frame = new JFrame( "MyFrameWithComponen")
29 |
30 | JButton jbtOK = new JButton("OK"); // Add a button into the frame
31 | frame.add(jbtOK);
32 |
33 | frame.setSize(400, 300);
34 | frame.setDefau1tC10seOperation(JFrame.EXIT_ON_CLOSE);
35 | frame.setLocationRe1ativeTo(nu11); // Center the frame
36 | frame.setVisib1e(true);
37 | }
38 | }
39 | ```
40 | - [JFrame with inheritence](programs/MyFrame1.java)
41 |
42 | ### Layout Manager
43 | - For arraning a position into containers
44 |
45 | - [FlowLayout](programs/ShowFlowLayout.java)
46 |
47 | - [GridLayout](programs/ShowGridLayout.java)
48 |
49 | - [BorderLayout](programs/ShowBorderLayout.java)
50 |
51 | - `Color` class
52 | - ```java
53 | Color mycolor = new Color(228, 100, 50);
54 | // how to set for button
55 | mybutton.setBackground(Color.mycolor);
56 | mybutton.setForeground(Color.mycolor);
57 | ```
58 |
59 | ### JPanel
60 | - In `JFrame` we add a component `JPanel`
61 |
62 | - [TestPanels](programs/TestPanels.java)
63 |
64 | ### Event-Handling in Java (Event-Driven Programming)
65 |
66 | - [Lecture Notes](lecture-notes/Event-Driven_Programming.ppt)
67 |
68 | - Event-driven programming (depends of action) <-> procedural programming (step by step)
69 |
70 | - [HandleEvent](programs/HandleEvent.java)
71 |
72 | - [HandleEvent1](programs/HandleEvent1.java) with the use of Inner Classes
73 |
74 | - ```
75 | User Action Object Generated
76 |
77 | Click a button JButton ActionEvent
78 | Click a check box JCheckBox ItemEvent, ActionEvent
79 | Click a radio button JRadioButton ItemEvent, ActionEvent
80 | Press return on a text field JTextField ActionEvent
81 | Select a new item JComboBox ItemEvent, ActionEvent
82 | Window opened, closed, etc. Window WindowEvent
83 | Mouse pressed, released, etc. Component MouseEvent
84 | Key released, pressed, etc. Component KeyEvent
85 | ```
86 |
87 | - ```
88 | Event Class Listener Interface Listener Methods (Handlers)
89 | ActionEvent ActionListener actionPerformed(ActionEvent)
90 | ItemEvent ItemListener itemStateChanged(ItemEvent)
91 | WindowEvent WindowListener windowClosing(WindowEvent)
92 | windowOpened(WindowEvent)
93 | windowIconified(WindowEvent)
94 | windowDeiconified(WindowEvent)
95 | windowClosed(WindowEvent)
96 | windowActivated(WindowEvent)
97 | windowDeactivated(WindowEvent)
98 | ContainerEvent ContainerListener componentAdded(ContainerEvent)
99 | componentRemoved(ContainerEvent)
100 | MouseEvent MouseListener mousePressed(MouseEvent)
101 | mouseReleased(MouseEvent)
102 | mouseClicked(MouseEvent)
103 | mouseExited(MouseEvent)
104 | mouseEntered(MouseEvent)
105 | KeyEvent KeyListener keyPressed(KeyEvent)
106 | keyReleased(KeyEvent)
107 | keyTypeed(KeyEvent)
108 |
109 | ```
110 |
--------------------------------------------------------------------------------
/lab-02/App.java:
--------------------------------------------------------------------------------
1 | /* Student: Rustam Zokirov
2 | ID: U1910049
3 | Lab: #2 BMI Calculator
4 | */
5 | import java.util.Scanner; // Import the Scanner class
6 |
7 | public class App { // Create a Class App
8 | public static void main(String[] args){
9 | Scanner input = new Scanner(System.in); // Create a scanner object
10 | int choice;
11 | boolean isCalculate = true;
12 | float height = 0, weight = 0, BMI;
13 | int choice2;
14 |
15 | while(isCalculate) {
16 | System.out.println("*** Welcome to BMI Calculator! ***");
17 | System.out.println("Please enter only numbers!\n" + "1. Kilograms and meters\n" + "2. Pounds and inches\n" + "0. Exit\n" + "Choose option: ");
18 | choice = input.nextInt();
19 |
20 | switch (choice) {
21 | case 0: {
22 | isCalculate = false;
23 | }break;
24 | case 1: { // Kilograms and meters
25 | for (int i = 0; i == 0; ) { //taking data from user and check for validation
26 | System.out.println("Enter height (meters): ");
27 | height = input.nextFloat();
28 | System.out.println("Enter weight (kg): ");
29 | weight = input.nextFloat();
30 |
31 | if (height > 0 && weight > 0)
32 | i = 1;
33 | else
34 | System.out.println("Enter correct values!");
35 |
36 | }
37 |
38 | BMI = weight / (height * height);
39 |
40 | if (BMI < 18.5)
41 | System.out.printf("BMI: %.2f Underweight", BMI);
42 | else if (BMI >= 18.5 && BMI < 25)
43 | System.out.printf("BMI: %.2f Normal", BMI);
44 | else if (BMI >= 25 && BMI < 30)
45 | System.out.printf("BMI: %.2f Overweight", BMI);
46 | else if (BMI >= 30 && BMI < 35)
47 | System.out.printf("BMI: %.2f Obese", BMI);
48 | else
49 | System.out.printf("BMI: %.2f Extremely Obese", BMI);
50 |
51 | System.out.println("\nDo you want to calculate again? (1. YES / Any key. NO)");
52 | choice2 = input.nextInt();
53 |
54 | if (choice2 != 1)
55 | isCalculate = false;
56 |
57 | }break;
58 | case 2: { // Pounds and inches
59 | for (int i = 0; i == 0; ) { //taking data from user and check for validation
60 | System.out.println("Enter height (inches): ");
61 | height = input.nextFloat();
62 | System.out.println("Enter weight (pounds): ");
63 | weight = input.nextFloat();
64 |
65 | if (height > 0 && weight > 0)
66 | i = 1;
67 | else
68 | System.out.println("Enter correct values!");
69 |
70 | }
71 |
72 | BMI = 703 * weight / (height * height);
73 |
74 | if (BMI < 18.5)
75 | System.out.printf("BMI: %.2f Underweight", BMI);
76 | else if (BMI >= 18.5 && BMI < 25)
77 | System.out.printf("BMI: %.2f Normal", BMI);
78 | else if (BMI >= 25 && BMI <= 30)
79 | System.out.printf("BMI: %.2f Overweight", BMI);
80 | else if (BMI >= 30 && BMI <= 35)
81 | System.out.printf("BMI: %.2f Obese", BMI);
82 | else
83 | System.out.printf("BMI: %.2f Extremely Obese", BMI);
84 |
85 | System.out.println("\nDo you want to calculate again? (1. YES / 0. NO) ");
86 | choice2 = input.nextInt();
87 |
88 | if (choice2 != 1)
89 | isCalculate = false;
90 |
91 | }break;
92 | default: {
93 | System.out.println("Please enter correct values!");
94 | }break;
95 | } // switch
96 |
97 | } //while
98 |
99 | } // main()
100 |
101 | } // Class App
102 |
--------------------------------------------------------------------------------
/lab-07-javafx/PrinterJavaFX.java:
--------------------------------------------------------------------------------
1 | /*
2 | By Rustam Zokirov,
3 | U1910049
4 | Lab: #7
5 | Printer Application
6 | */
7 |
8 | // import some libraries
9 | import javafx.application.Application;
10 | import javafx.stage.Stage;
11 | import javafx.scene.Scene;
12 | import javafx.scene.Group;
13 | import javafx.scene.layout.StackPane;
14 | import javafx.scene.text.Text;
15 | import javafx.scene.transform.Scale;
16 | import javafx.scene.control.TextArea;
17 | import javafx.scene.control.CheckBox;
18 | import javafx.scene.control.RadioButton;
19 | import javafx.scene.control.ComboBox;
20 | import javafx.scene.control.Button;
21 | import javafx.scene.control.Label;
22 |
23 | public class PrinterJavaFX extends Application {
24 |
25 | @Override
26 | public void start(Stage primaryStage) throws Exception {
27 |
28 | Label labelPrinter = new Label("Printer: My Printer");
29 | labelPrinter.setLayoutX(30);
30 | labelPrinter.setLayoutY(10);
31 | labelPrinter.setPrefSize(150, 20);
32 |
33 | Label txtQuality = new Label("Print Quality: ");
34 | txtQuality.setLayoutX(30);
35 | txtQuality.setLayoutY(100);
36 | txtQuality.setPrefSize(150, 20);
37 |
38 | TextArea labelType = new TextArea();
39 | labelType.setLayoutX(25);
40 | labelType.setLayoutY(35);
41 | labelType.setPrefSize(50, 60);
42 |
43 | TextArea txtSize = new TextArea();
44 | txtSize.setLayoutX(150);
45 | txtSize.setLayoutY(35);
46 | txtSize.setPrefSize(40, 60);
47 |
48 | TextArea txtSpace = new TextArea();
49 | txtSpace.setLayoutX(270);
50 | txtSpace.setLayoutY(35);
51 | txtSpace.setPrefSize(50, 60);
52 |
53 | CheckBox checkImage = new CheckBox("Image");
54 | checkImage.setLayoutX(75);
55 | checkImage.setLayoutY(37);
56 | checkImage.setPrefSize(70, 20);
57 |
58 | CheckBox checkText = new CheckBox("Text");
59 | checkText.setLayoutX(75);
60 | checkText.setLayoutY(57);
61 | checkText.setPrefSize(70, 20);
62 |
63 | CheckBox checkCode = new CheckBox("Code");
64 | checkCode.setLayoutX(75);
65 | checkCode.setLayoutY(77);
66 | checkCode.setPrefSize(70, 20);
67 |
68 | CheckBox checkPrint = new CheckBox("Print to File");
69 | checkPrint.setLayoutX(220);
70 | checkPrint.setLayoutY(100);
71 | checkPrint.setPrefSize(100, 20);
72 |
73 | RadioButton radioSelect = new RadioButton("Select");
74 | radioSelect.setLayoutX(190);
75 | radioSelect.setLayoutY(37);
76 | radioSelect.setPrefSize(70, 20);
77 |
78 | RadioButton radioAll = new RadioButton("All");
79 | radioAll.setLayoutX(190);
80 | radioAll.setLayoutY(57);
81 | radioAll.setPrefSize(70, 20);
82 |
83 | RadioButton radioApplet = new RadioButton("Applet");
84 | radioApplet.setLayoutX(190);
85 | radioApplet.setLayoutY(77);
86 | radioApplet.setPrefSize(70, 20);
87 |
88 | ComboBox comboQuality = new ComboBox();
89 | comboQuality.getItems().add("High");
90 | comboQuality.getItems().add("Middle");
91 | comboQuality.getItems().add("Low");
92 | comboQuality.setLayoutX(115);
93 | comboQuality.setLayoutY(100);
94 | comboQuality.setPrefSize(75, 20);
95 |
96 | Button buttonOk = new Button("OK");
97 | buttonOk.setLayoutX(330);
98 | buttonOk.setLayoutY(20);
99 | buttonOk.setPrefSize(80, 30);
100 |
101 | Button buttonCancel = new Button("Cancel");
102 | buttonCancel.setLayoutX(330);
103 | buttonCancel.setLayoutY(50);
104 | buttonCancel.setPrefSize(80, 30);
105 |
106 | Button buttonSetup = new Button("Setup...");
107 | buttonSetup.setLayoutX(330);
108 | buttonSetup.setLayoutY(80);
109 | buttonSetup.setPrefSize(80, 30);
110 |
111 | Button buttonHelp = new Button("Help");
112 | buttonHelp.setLayoutX(330);
113 | buttonHelp.setLayoutY(110);
114 | buttonHelp.setPrefSize(80, 30);
115 |
116 | Group root = new Group();
117 |
118 | root.getChildren().add(labelPrinter);
119 | root.getChildren().add(txtQuality);
120 | root.getChildren().add(labelType);
121 | root.getChildren().add(txtSize);
122 | root.getChildren().add(txtSpace);
123 | root.getChildren().add(checkImage);
124 | root.getChildren().add(checkCode);
125 | root.getChildren().add(checkPrint);
126 | root.getChildren().add(checkText);
127 | root.getChildren().add(radioAll);
128 | root.getChildren().add(radioApplet);
129 | root.getChildren().add(radioSelect);
130 | root.getChildren().add(comboQuality);
131 | root.getChildren().add(buttonCancel);
132 | root.getChildren().add(buttonHelp);
133 | root.getChildren().add(buttonOk);
134 | root.getChildren().add(buttonSetup);
135 |
136 | // New scene
137 | Scene scene = new Scene(root, 450, 200);
138 |
139 | primaryStage.setScene(scene);
140 | primaryStage.setTitle("Printer");
141 | primaryStage.show();
142 |
143 | }
144 | public static void main(String[] args) {
145 | launch(args); // running app
146 | }
147 | }
--------------------------------------------------------------------------------
/lab-07-javafx/CalculatorJavaFX.java:
--------------------------------------------------------------------------------
1 | /*
2 | By Rustam Zokirov,
3 | U1910049
4 | Lab: #7
5 | Calculator Application
6 | */
7 |
8 | // import libraries
9 | import javafx.application.Application;
10 | import javafx.scene.Scene;
11 | import javafx.stage.Stage;
12 | import javafx.scene.control.Button;
13 | import javafx.scene.control.Label;
14 | import javafx.scene.control.TextField;
15 | import javafx.scene.layout.GridPane;
16 | import javafx.scene.layout.HBox;
17 | import javafx.event.EventHandler;
18 | import javafx.event.ActionEvent;
19 |
20 | public class CalculatorJavaFX extends Application {
21 | String value; // text value
22 | String math; // calculations, +, -, *, /
23 | double num1, num2, result; // number 1, number 2, result
24 |
25 | @Override
26 | public void start(Stage stage) throws Exception {
27 | // Text
28 | TextField textField = new TextField();
29 |
30 | // Buttons
31 | Button bOne = new Button("1");
32 | Button bTwo = new Button("2");
33 | Button bThree = new Button("3");
34 | Button bFour = new Button("4");
35 | Button bFive = new Button("5");
36 | Button bSix = new Button("6");
37 | Button bSeven = new Button("7");
38 | Button bEight = new Button("8");
39 | Button bNine = new Button("9");
40 | Button bZero = new Button("0");
41 | Button bAdd = new Button("+");
42 | Button bSub = new Button("-");
43 | Button bMul = new Button("*");
44 | Button bDiv = new Button("/");
45 | Button bEqual = new Button("=");
46 | Button bDot = new Button(".");
47 |
48 | // lambdas
49 | bZero.setOnAction(e -> textField.setText(textField.getText() + "0"));
50 | bOne.setOnAction(e -> textField.setText(textField.getText() + "1"));
51 | bTwo.setOnAction(e -> textField.setText(textField.getText() + "2"));
52 | bThree.setOnAction(e -> textField.setText(textField.getText() + "3"));
53 | bFour.setOnAction(e -> textField.setText(textField.getText() + "4"));
54 | bFive.setOnAction(e -> textField.setText(textField.getText() + "5"));
55 | bSix.setOnAction(e -> textField.setText(textField.getText() + "6"));
56 | bSeven.setOnAction(e -> textField.setText(textField.getText() + "7"));
57 | bEight.setOnAction(e -> textField.setText(textField.getText() + "8"));
58 | bNine.setOnAction(e -> textField.setText(textField.getText() + "9"));
59 | bDot.setOnAction(e -> textField.setText(textField.getText() + "."));
60 |
61 | bAdd.setOnAction(new EventHandler(){
62 | @Override
63 | public void handle(ActionEvent event) {
64 | math = "Add";
65 | value = textField.getText();
66 | num1 = Double.parseDouble(value);
67 | textField.setText("");
68 | }
69 | });
70 | bSub.setOnAction(new EventHandler(){
71 | @Override
72 | public void handle(ActionEvent event) {
73 | math = "Sub";
74 | value = textField.getText();
75 | num1 = Double.parseDouble(value);
76 | textField.setText("");
77 | }
78 | });
79 | bMul.setOnAction(new EventHandler(){
80 | @Override
81 | public void handle(ActionEvent event) {
82 | math = "Mul";
83 | value = textField.getText();
84 | num1 = Double.parseDouble(value);
85 | textField.setText("");
86 | }
87 | });
88 | bDiv.setOnAction(new EventHandler(){
89 | @Override
90 | public void handle(ActionEvent event) {
91 | math = "Div";
92 | value = textField.getText();
93 | num1 = Double.parseDouble(value);
94 | textField.setText("");
95 | }
96 | });
97 |
98 | bEqual.setOnAction(new EventHandler(){
99 | @Override
100 | public void handle(ActionEvent event) {
101 | value = textField.getText();
102 | num2 = Double.parseDouble(value); // get the last value
103 | switch (math) {
104 | case "Div": result = num1 / num2;
105 | break;
106 | case "Mul": result = num1 * num2;
107 | break;
108 | case "Add": result = num1 + num2;
109 | break;
110 | case "Sub": result = num1 - num2;
111 | break;
112 | }
113 | textField.setText("" + result);
114 | }
115 | });
116 |
117 | // set layout to gridpane
118 | GridPane gridPane = new GridPane();
119 |
120 | gridPane.add(textField, 0, 0);
121 |
122 | gridPane.add(bSeven, 1, 0);
123 | gridPane.add(bEight, 1, 1);
124 | gridPane.add(bNine, 1, 2);
125 | gridPane.add(bDiv, 1, 3);
126 |
127 | gridPane.add(bFour, 2, 0);
128 | gridPane.add(bFive, 2, 1);
129 | gridPane.add(bSix, 2, 2);
130 | gridPane.add(bMul, 2, 3);
131 |
132 | gridPane.add(bOne, 3, 0);
133 | gridPane.add(bTwo, 3, 1);
134 | gridPane.add(bThree, 3, 2);
135 | gridPane.add(bSub, 3, 3);
136 |
137 | gridPane.add(bZero, 4, 0);
138 | gridPane.add(bDot, 4, 1);
139 | gridPane.add(bEqual, 4, 2);
140 | gridPane.add(bAdd, 4, 3);
141 |
142 | Scene scene = new Scene(gridPane);
143 |
144 | stage.setScene(scene);
145 | stage.setTitle("Calculator");
146 | stage.show();
147 | }
148 | public static void main(String[] args) {
149 | Application.launch(args); // running
150 | }
151 | }
152 |
--------------------------------------------------------------------------------
/lab-06-swing/Calculator.java:
--------------------------------------------------------------------------------
1 | /*
2 | By Rustam Zokirov,
3 | U190049
4 | Lab: #6
5 | Calculator Application
6 | */
7 |
8 | // import some libraries
9 | import javax.swing.*;
10 | import java.awt.*;
11 | import java.awt.event.*;
12 |
13 | public class Calculator extends JFrame {
14 | JTextField jtxtField = new JTextField(); // text field
15 | JButton jbt0Button = new JButton("0"); // some buttons from 0-9
16 | JButton jbt1Button = new JButton("1");
17 | JButton jbt2Button = new JButton("2");
18 | JButton jbt3Button = new JButton("3");
19 | JButton jbt4Button = new JButton("4");
20 | JButton jbt5Button = new JButton("5");
21 | JButton jbt6Button = new JButton("6");
22 | JButton jbt7Button = new JButton("7");
23 | JButton jbt8Button = new JButton("8");
24 | JButton jbt9Button = new JButton("9");
25 | JButton jbtDeleteButton = new JButton("/"); // operations
26 | JButton jbtMultiplyButton = new JButton("*");
27 | JButton jbtMinusButton = new JButton("-");
28 | JButton jbtPlusButton = new JButton("+");
29 | JButton jbtEqualButton = new JButton("=");
30 | JButton jbtDotButton = new JButton(".");
31 |
32 | public Calculator() {
33 | // Panel for the text field
34 | JPanel panel_text = new JPanel();
35 | panel_text.setLayout(new BorderLayout()); // implementing BorderLayout
36 | panel_text.add(jtxtField, BorderLayout.NORTH);
37 |
38 | // Create a panel to hold buttons
39 | JPanel panel = new JPanel();
40 | panel.setLayout(new GridLayout(4, 4)); // implementing GridLayout 4 by 4
41 | panel.add(jbt7Button);
42 | panel.add(jbt8Button);
43 | panel.add(jbt9Button);
44 | panel.add(jbtDeleteButton);
45 | panel.add(jbt4Button);
46 | panel.add(jbt5Button);
47 | panel.add(jbt6Button);
48 | panel.add(jbtMultiplyButton);
49 | panel.add(jbt1Button);
50 | panel.add(jbt2Button);
51 | panel.add(jbt3Button);
52 | panel.add(jbtMinusButton);
53 | panel.add(jbt0Button);
54 | panel.add(jbtDotButton);
55 | panel.add(jbtEqualButton);
56 | panel.add(jbtPlusButton);
57 |
58 | panel_text.add(panel, BorderLayout.CENTER);
59 | add(panel_text); // Add panel to the frame
60 |
61 | // Register listeners
62 | ListenerClass listener = new ListenerClass();
63 | jbt0Button.addActionListener(listener);
64 | jbt1Button.addActionListener(listener);
65 | jbt2Button.addActionListener(listener);
66 | jbt3Button.addActionListener(listener);
67 | jbt4Button.addActionListener(listener);
68 | jbt5Button.addActionListener(listener);
69 | jbt6Button.addActionListener(listener);
70 | jbt7Button.addActionListener(listener);
71 | jbt8Button.addActionListener(listener);
72 | jbt9Button.addActionListener(listener);
73 | jbtPlusButton.addActionListener(listener);
74 | jbtMinusButton.addActionListener(listener);
75 | jbtMultiplyButton.addActionListener(listener);
76 | jbtDeleteButton.addActionListener(listener);
77 | jbtEqualButton.addActionListener(listener);
78 | jbtDotButton.addActionListener(listener);
79 | }
80 |
81 | public static void main(String[] args) {
82 | JFrame frame = new Calculator(); // creating object
83 | frame.setTitle("Handle Event");
84 | frame.setSize(200, 200); // set size
85 | frame.setLocation(200, 100); // set location in window
86 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
87 | frame.setVisible(true);
88 | }
89 |
90 | // ListenerClass - Inner Class for handing the actions
91 | class ListenerClass implements ActionListener {
92 | char operation; // operation
93 | double num1; // number 1
94 | double num2; // number 2
95 | double result; // result
96 |
97 | public void actionPerformed(ActionEvent e) {
98 | // handle the text field
99 | if (e.getSource() == jbt0Button)
100 | jtxtField.setText(jtxtField.getText() + '0');
101 | else if (e.getSource() == jbt1Button)
102 | jtxtField.setText(jtxtField.getText() + '1');
103 | else if (e.getSource() == jbt2Button)
104 | jtxtField.setText(jtxtField.getText() + '2');
105 | else if (e.getSource() == jbt3Button)
106 | jtxtField.setText(jtxtField.getText() + '3');
107 | else if (e.getSource() == jbt5Button)
108 | jtxtField.setText(jtxtField.getText() + '5');
109 | else if (e.getSource() == jbt6Button)
110 | jtxtField.setText(jtxtField.getText() + '6');
111 | else if (e.getSource() == jbt7Button)
112 | jtxtField.setText(jtxtField.getText() + '7');
113 | else if (e.getSource() == jbt8Button)
114 | jtxtField.setText(jtxtField.getText() + '8');
115 | else if (e.getSource() == jbt9Button)
116 | jtxtField.setText(jtxtField.getText() + '9');
117 | else if (e.getSource() == jbtDotButton)
118 | jtxtField.setText(jtxtField.getText() + '.');
119 | else if (e.getSource() == jbtPlusButton) {
120 | operation = '+';
121 | num1 = Double.parseDouble(jtxtField.getText());
122 | jtxtField.setText("");
123 | }
124 | else if (e.getSource() == jbtMinusButton) {
125 | operation = '-';
126 | num1 = Double.parseDouble(jtxtField.getText());
127 | jtxtField.setText("");
128 | }
129 | else if (e.getSource() == jbtMultiplyButton) {
130 | operation = '*';
131 | num1 = Double.parseDouble(jtxtField.getText());
132 | jtxtField.setText("");
133 | }
134 | else if (e.getSource() == jbtDeleteButton) {
135 | operation = '/';
136 | num1 = Double.parseDouble(jtxtField.getText());
137 | jtxtField.setText("");
138 | }
139 | else if (e.getSource() == jbtEqualButton) {
140 | num2 = Double.parseDouble(jtxtField.getText());
141 |
142 | // handle calculation
143 | if (operation == '+')
144 | result = num1 + num2;
145 | else if (operation == '-')
146 | result = num1 - num2;
147 | else if (operation == '*')
148 | result = num1 * num2;
149 | else if (operation == '/')
150 | result = num1 / num2;
151 |
152 | jtxtField.setText(Double.toString(result)); // ouput the resust
153 | }
154 | }
155 | } // ListenerClass
156 | } // Calculator
157 |
--------------------------------------------------------------------------------
/lab-08-mysql/IUT_BMI.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner; // Import the Scanner class
2 | import java.sql.*; // Use 'Connection', 'Statement' and 'ResultSet' classes in java.sql package
3 |
4 | public class IUT_BMI {
5 | public static void main(String[] args) {
6 |
7 | try (
8 | // Allocate a database 'Connection' object
9 | Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/IUT_BMI?autoReconnect=true&useSSL=false", "root", "1234");
10 |
11 | // Allocate a 'Statement' object in the Connection
12 | Statement stmt = conn.createStatement();
13 | ) {
14 |
15 | Scanner input = new Scanner(System.in); // Create a Scanner object
16 | int option, isExit; // Initializing some variables
17 |
18 | int employeeID, employeeHeight, employeeWeight;
19 | String employeeName;
20 |
21 | do { // Loop for reusing the program
22 | option = showMenu(); // The option value
23 |
24 | switch (option){
25 | case 1:
26 | System.out.println("***** DISPLAY RECORDS *****");
27 | // Execute a SQL SELECT query, the query result is returned in a 'ResultSet' object.
28 | String strSelect = "SELECT * FROM Employee_BMI; ";
29 | System.out.println("The SQL query is: " + strSelect); // Echo For debugging
30 | System.out.println();
31 |
32 | ResultSet rset = stmt.executeQuery(strSelect);
33 |
34 | // Process the ResultSet by scrolling the cursor forward via next().
35 | // For each row, retrieve the contents of the cells with getXxx(columnName).
36 | System.out.println("The records selected are:");
37 | int rowCount = 0;
38 |
39 | while(rset.next()) { // Move the cursor to the next row, return false if no more row
40 | employeeID = rset.getInt("employeeID");
41 | employeeHeight = rset.getInt("employeeHeight");
42 | employeeWeight = rset.getInt("employeeWeight");
43 | employeeName = rset.getString("employeeName");
44 |
45 | System.out.println(employeeID + " " + employeeName + " " + employeeHeight + " " + employeeWeight );
46 | rowCount++;
47 | }
48 | System.out.println("Total number of records = " + rowCount);
49 | break;
50 |
51 | case 2:
52 | System.out.println("***** INSERT RECORD *****");
53 | //Execute a SQL SELECT query, the query result is returned in a 'ResultSet' object.
54 | System.out.print("Employee ID: "); employeeID = (input.nextInt());
55 | System.out.print("Employee height: "); employeeHeight = (input.nextInt());
56 | System.out.print("Employee weight: "); employeeWeight = (input.nextInt());
57 | System.out.print("Employee name: "); employeeName = (input.next());
58 |
59 | strSelect = "INSERT INTO Employee_BMI VALUES(" + employeeID + "," + "'" + employeeName + "'," + " " + employeeHeight+"," + " " + employeeWeight+")";
60 |
61 | System.out.println("The SQL query is: " + strSelect); // Echo For debugging
62 |
63 | int count = stmt.executeUpdate(strSelect);
64 |
65 | break;
66 |
67 | case 3:
68 | System.out.println("***** UPDATE RECORD *****");
69 | // Execute a SQL SELECT query, the query result is returned in a 'ResultSet' object.
70 | System.out.print("Employee ID: "); employeeID = (input.nextInt());
71 | System.out.print("Employee height: "); employeeHeight = (input.nextInt());
72 | System.out.print("Employee weight: "); employeeWeight = (input.nextInt());
73 |
74 | // SQL query to update record
75 | strSelect ="UPDATE Employee_BMI SET employeeWeight=" + employeeWeight + ", employeeHeight=" + employeeHeight + " WHERE employeeID="+ employeeID;
76 |
77 | System.out.println("The SQL query is: " + strSelect); // Echo For debugging
78 |
79 | count = stmt.executeUpdate(strSelect);
80 |
81 | break;
82 |
83 | case 4:
84 | System.out.println("***** DELETE RECORD *****");
85 | // Execute a SQL SELECT query, the query result is returned in a 'ResultSet' object.
86 | System.out.print("Employee ID: "); employeeID = (input.nextInt());
87 |
88 | // to delete record
89 | strSelect ="DELETE FROM Employee_BMI WHERE employeeID=" + employeeID;
90 |
91 | System.out.println("The SQL query is: " + strSelect); // Echo For debugging
92 | System.out.println();
93 |
94 | count = stmt.executeUpdate(strSelect);
95 | break;
96 |
97 | case 0:
98 | System.out.println("Quitting Program...");
99 | System.exit(0); // program ends
100 | break;
101 | default:
102 | System.out.println("Please choose a valid option!");
103 |
104 | } // End of switch
105 |
106 | System.out.print("\nDo you want to continue? (0.No 1.Yes) - ");
107 | isExit = input.nextInt(); // validation checking
108 |
109 | } while(isExit == 1);
110 |
111 |
112 | } catch(SQLException ex) {
113 | ex.printStackTrace();
114 | }
115 |
116 | } // end of main()
117 |
118 | public static int showMenu() {
119 | Scanner input = new Scanner(System.in); // Create a Scanner object
120 |
121 | int option = 0;
122 | // Printing menu to screen
123 | System.out.println("\n***** MAIN MENU *****");
124 | System.out.println("1. Display records");
125 | System.out.println("2. Insert record");
126 | System.out.println("3. Update record");
127 | System.out.println("4. Delete record");
128 | System.out.println("0. Exit");
129 |
130 | // Getting user option from above menu
131 | System.out.print("Your choice: ");
132 | option = input.nextInt();
133 | System.out.println();
134 |
135 | return option;
136 | } // End of showMenu
137 | }
138 |
--------------------------------------------------------------------------------
/lab-04/DoMApplication.java:
--------------------------------------------------------------------------------
1 | /*
2 | Student: Rustam Zokirov
3 | StudentID: U1910049
4 | Lab #4: DoM Application
5 | */
6 |
7 | import java.util.Scanner; // Import Snanner class
8 | import java.util.Random; // Import Random class
9 |
10 | class DoMApplication {
11 |
12 | public static void main(String[] args) { // main() method
13 | Scanner input = new Scanner(System.in); // Create a Scanner object
14 | int option, isExit; // Initializing some variables
15 |
16 | CityTemperature temperature = new CityTemperature(); // Create object of CityTemperature
17 | CityRainFall rainFall = new CityRainFall(); // Create object of CityRainFall
18 |
19 | do { // Loop for reusing the program
20 | option = showMenu(); // The option value
21 |
22 | switch (option){
23 | case 1:
24 | temperature.viewCityInfo(); // show city info
25 | break;
26 |
27 | case 2:
28 | temperature.viewClimateData(); // show city temperature info
29 | break;
30 |
31 | case 3:
32 | rainFall.viewClimateData(); // show city rainfall info
33 | break;
34 |
35 | case 4:
36 | int ID;
37 | String name;
38 |
39 | System.out.print("Enter the city ID: ");
40 | ID = input.nextInt(); // get user's input
41 | temperature.setCityID(ID); // set city new ID
42 |
43 | System.out.print("Enter the city name: ");
44 | name = input.next(); // get user's input
45 | temperature.setCityName(name); // set city new name
46 |
47 | break;
48 | case 5:
49 | double[] cityClimateData = new double[24]; // create an array
50 |
51 | for(int j=0; j<24; j++) {
52 | System.out.print("Enter climate data for " + j + ":00: ");
53 | cityClimateData[j] = input.nextDouble(); // take user's input
54 | }
55 | temperature.setClimateData(cityClimateData); // set the new temperature data
56 | break;
57 |
58 | case 6:
59 | double[] cityRainFallData = new double[12]; // create an array
60 |
61 | for(int k=0; k<12; k++) {
62 | System.out.print("Enter rainfall data for month #" + (k+1) + ": ");
63 | cityRainFallData[k] = input.nextDouble(); // take user's inputs
64 | }
65 | rainFall.setClimateData(cityRainFallData); // set the new rainfall data
66 | break;
67 |
68 | case 0:
69 | System.out.println("Quitting Program...");
70 | System.exit(0); // program ends
71 | break;
72 |
73 | default:
74 | System.out.println("Sorry, please enter valid option!");
75 | } // End of switch
76 |
77 | System.out.print("\nDo you want to continue? (0.No 1.Yes) - ");
78 | isExit = input.nextInt(); // validation checking
79 |
80 | } while(isExit == 1);
81 | } // End of main
82 |
83 | public static int showMenu() {
84 | Scanner input = new Scanner(System.in); // Create a Scanner object
85 |
86 | int option = 0;
87 | // Printing menu to screen
88 | System.out.println("\n***** MAIN MENU *****");
89 | System.out.println("1. City information");
90 | System.out.println("2. City temperature (24 hours)");
91 | System.out.println("3. City rainfall (12 months)");
92 | System.out.println("4. Set city information");
93 | System.out.println("5. Set city temperature (24 hours)");
94 | System.out.println("6. Set city rainfall (12 months)");
95 | System.out.println("0. Exit");
96 |
97 | // Getting user option from above menu
98 | System.out.print("Your choice: ");
99 | option = input.nextInt();
100 | System.out.println();
101 |
102 | return option;
103 | } // End of showMenu
104 | }
105 |
106 | class City {
107 | private int cityID; // private = restricted access
108 | private String cityName; // private = restricted access
109 |
110 | City() { // Default constructor
111 | cityID = 49;
112 | cityName = "Silicon Valley";
113 | }
114 |
115 | City(int cityID, String cityName) { // Parametrized constructor
116 | this.cityID = cityID;
117 | this.cityName = cityName;
118 | }
119 |
120 | // Getter for cityID
121 | public int getCityID() {
122 | return cityID;
123 | }
124 |
125 | // Setter for cityID
126 | public void setCityID(int cityID) {
127 | this.cityID = cityID;
128 | }
129 |
130 | // Getter for cityName
131 | public String getCityName() {
132 | return cityName;
133 | }
134 |
135 | // Setter for cityName
136 | public void setCityName(String cityName) {
137 | this.cityName = cityName;
138 | }
139 |
140 | // Viewer for CityInfo: Id, Name
141 | public void viewCityInfo() {
142 | System.out.println("City ID: " + getCityID());
143 | System.out.println("City Name: " + getCityName());
144 | }
145 | }
146 |
147 | class CityTemperature extends City{
148 | private double[] cityClimateData = {};
149 |
150 | CityTemperature() {
151 | cityClimateData = new double[24];
152 |
153 | for(int i=0; i<24; i++) { // Set to default 0
154 | cityClimateData[i] = i+20;
155 | }
156 | }
157 |
158 | public void setClimateData(double[] cityClimateData) {
159 | this.cityClimateData = cityClimateData;
160 | }
161 |
162 | // Getter for cityClimateData
163 | public double[] getClimateData() {
164 | return cityClimateData;
165 | }
166 |
167 | public void viewClimateData() {
168 | for(int i=0; i<24; i++) { // Set to default 0
169 | System.out.println("Time: " + i + ":00 = " + cityClimateData[i] + " C");
170 | }
171 | }
172 | }
173 |
174 | class CityRainFall extends City {
175 | private double[] cityClimateData = {}; // data member
176 |
177 | CityRainFall() { // default constructor
178 | Random random = new Random(); // Create an object of Random class
179 | cityClimateData = new double[12]; // Create an array
180 |
181 | for(int i=0; i<12; i++) { // Set to default 0
182 | int rand_num = random.nextInt(200);
183 | cityClimateData[i] = rand_num + 500; // Initialize the elements
184 | }
185 | }
186 |
187 | public void setClimateData(double[] cityClimateData) {
188 | this.cityClimateData = cityClimateData;
189 | }
190 |
191 | // Getter for cityClimateData
192 | public double[] getClimateData() {
193 | return cityClimateData;
194 | }
195 |
196 | // Viewer for ClimateData
197 | public void viewClimateData() {
198 | for(int i=0; i<12; i++) { // Set to default 0
199 | System.out.println("Month #" + (i+1) +": " + cityClimateData[i] + " mm");
200 | }
201 | }
202 | }
203 |
--------------------------------------------------------------------------------
/lab-03/MobileTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | Rustam Zokirov, U1910049
3 | Lab Assignment #3
4 | */
5 |
6 | import java.util.Scanner; // import Scanner class
7 |
8 | class Mobile { // Mobile class
9 | // attributes of class
10 | private String company, model; // model and company of phone
11 | private boolean isOn, hasCamera; // booleans isOn and hasCamera
12 | private int memory, volume; // volume from 0 to 10
13 |
14 | public Mobile(){ // default constructor
15 | company = "Samsung";
16 | model = "Z Fold 2";
17 | isOn = true;
18 | hasCamera = true;
19 | memory = 512;
20 | volume = 10;
21 | } // End
22 |
23 | public Mobile(String company,String model, boolean isOn, boolean hasCamera, int memory, int volume){ // parametrized constructor
24 | this.company = company;
25 | this.model = model;
26 | this.isOn = isOn;
27 | this.hasCamera = hasCamera;
28 | this.memory = memory;
29 | this.volume = volume;
30 | } // End
31 |
32 | public void setCompany(String company){ // Setter for company
33 | this.company = company;
34 | }
35 |
36 | public String getCompany(){ // Getter for company
37 | return company;
38 | }
39 |
40 | public void setModel(String model){ // Setter for model
41 | this.model = model;
42 | }
43 |
44 | public String getModel(){ // Getter for model
45 | return model;
46 | }
47 |
48 | public void setIsOn(boolean isOn){ // Setter for isOn
49 | this.isOn = isOn;
50 | }
51 |
52 | public boolean getIsOn(){ // Getter for isOn
53 | return isOn;
54 | }
55 |
56 | public void setHasCamera(boolean hasCamera){ // Setter for hasCamera
57 | this.hasCamera = hasCamera;
58 | }
59 |
60 | public boolean getHasCamera(){ // Getter for hasCamera
61 | return hasCamera;
62 | }
63 |
64 | public void setMemory(int memory){ // Setter for volume
65 | this.memory = memory;
66 | }
67 |
68 | public int getMemory(){ // Getter for volume
69 | return memory;
70 | }
71 |
72 | public void setVolume(int volume){ // Setter for volume
73 | this.volume = volume;
74 | }
75 |
76 | public int getVolume(){ // Getter for volume
77 | return volume;
78 | }
79 |
80 | public void switchOn(){
81 | if (!isOn) // Validating for on, off
82 | setIsOn(true);
83 | else
84 | System.out.println("\nMobile phone is already switched on!");
85 | } // End
86 |
87 | public void switchOff() {
88 | if (isOn) // Validating for on, off
89 | setIsOn(false);
90 | else
91 | System.out.println("\nMobile phone is already switched off");
92 | } // End
93 |
94 | public void increaseVolume() {
95 | if (isOn && volume < 10) {// validating volume (0, 10) and on, off
96 | volume++; // increasing volume
97 | System.out.println("Volume is " + getVolume()); // outputting the volume
98 | }
99 | else if (!isOn)
100 | System.out.println("\nMobile phone is switched off!");
101 | else
102 | System.out.println("\nVolume is 10!");
103 | }// End
104 |
105 | public void decreaseVolume() {
106 | if (isOn && volume >= 0) { // validating volume (0, 10) and on, off
107 | volume--; // decreasing volume
108 | System.out.println("Volume is " + getVolume()); // outputting the volume
109 | }
110 | else if (!isOn)
111 | System.out.println("\nMobile phone is switched off!");
112 | else
113 | System.out.println("\nVolume is 0!");
114 | } // End
115 |
116 | public void setDetail() { // this function will set all the needed info for object
117 | Scanner input = new Scanner(System.in); // Create a Scanner object
118 |
119 | System.out.println("\n***** Mobile phone details *****");
120 |
121 | System.out.println("Company: ");
122 | String inputCompany = input.next();
123 | setCompany(inputCompany); // setting the company to inputCompany
124 |
125 | System.out.println("\nModel: ");
126 | String inputModel = input.next();
127 | setModel(inputModel); // setting the model to inputModel
128 |
129 | setIsOn(true); // phone is On
130 |
131 | while(true){ // validating the input
132 | System.out.println("\nHas Camera? (1.Yes 2.No) ");
133 | int inputHasCamera= input.nextInt(); // taking the input
134 | if (inputHasCamera == 1) {
135 | setHasCamera(true); // setting the hasCamera
136 | break;
137 | }
138 | else if (inputHasCamera == 2) {
139 | setHasCamera(false); // setting the hasCamera
140 | break;
141 | }
142 | else{
143 | System.out.println("\nPlease enter values 1 or 2!");
144 | }
145 | }
146 |
147 | while (true){ // validation the memory input
148 | System.out.println("\nMemory: ");
149 | int inputMemory = input.nextInt();
150 |
151 | if(inputMemory > 0){
152 | setMemory(inputMemory);
153 | break;
154 | }
155 | else
156 | System.out.println("\nPlease enter correct values!");
157 | }
158 |
159 | while (true) { // validating the volume
160 | System.out.println("\nVolume (0, 10): ");
161 | int inputVolume = input.nextInt();
162 |
163 | if(inputVolume >= 0 && inputVolume <= 10){
164 | setVolume(inputVolume);
165 | break;
166 | }
167 | else
168 | System.out.println("\nPlease enter correct values!");
169 | } // End
170 | }
171 |
172 | public void getDetail(){
173 | System.out.println("\n***** Mobile phone details *****");
174 | System.out.println("Company: " + getCompany());
175 | System.out.println("Model: " + getModel());
176 | System.out.println("On: " + getIsOn());
177 | System.out.println("Has Camera: " + getHasCamera());
178 | System.out.println("Memory: " + getMemory());
179 | System.out.println("Volume: " + getVolume());
180 | }
181 | } // End
182 |
183 | public class MobileTest { // MobileTest class
184 | public static Scanner input = new Scanner(System.in); // Create a Scanner object
185 |
186 | public static void main(String[] args){ // main method
187 | int option, isExit; // initializing some variables
188 | Mobile mobile = new Mobile(); // creating object of Mobile
189 |
190 | do {
191 | option = showMenu(); // the option for switch
192 | switch (option){
193 | case 1:
194 | mobile.setDetail();
195 | break;
196 | case 2:
197 | mobile.getDetail();
198 | break;
199 | case 3:
200 | mobile.increaseVolume();
201 | break;
202 | case 4:
203 | mobile.decreaseVolume();
204 | break;
205 | case 5:
206 | mobile.switchOn();
207 | break;
208 | case 6:
209 | mobile.switchOff();
210 | break;
211 | case 0:
212 | System.out.println("Quitting Program...");
213 | System.exit(0); // program ends
214 | break;
215 | default:
216 | System.out.println("\nSorry, please enter valid option!");
217 | } // End of switch
218 |
219 | System.out.println("\n----------------------------------------------------------------------------");
220 | System.out.println("Do you want to continue? (1.Yes 2.No)");
221 | isExit = input.nextInt(); // valid-on
222 |
223 | } while(isExit == 1);
224 |
225 | } // End of main
226 |
227 | public static int showMenu() {
228 | int option = 0;
229 | // Printing menu to screen
230 | System.out.println("\n***** MAIN MENU *****");
231 | System.out.println("1. Set details");
232 | System.out.println("2. Get details");
233 | System.out.println("3. Increase volume");
234 | System.out.println("4. Decrease volume");
235 | System.out.println("5. Switch on");
236 | System.out.println("6. Switch off");
237 | System.out.println("0. Exit");
238 |
239 | // Getting user option from above menu
240 | System.out.println("Your choice: ");
241 | option = input.nextInt();
242 | // re
243 | return option;
244 | } // End of showMenu
245 | } // End of class MobileTest
246 |
--------------------------------------------------------------------------------
/lab-05/src/ProductDemo.java:
--------------------------------------------------------------------------------
1 | /*
2 | Student: Rustam Zokirov
3 | ID: U1910049
4 | Lab: #5
5 | */
6 |
7 | import java.net.PortUnreachableException;
8 | import java.util.Scanner; // import Scanner class
9 |
10 | // interface
11 | interface Operatable {
12 | public void increaseVolume();
13 | public void decreaseVolume();
14 | public void switchOn();
15 | public void switchOff();
16 | }
17 |
18 | // abstract class
19 | abstract class Product implements Operatable {
20 | private int productID;
21 | private String companyName;
22 | private String modelName;
23 | protected boolean isOn;
24 | protected int volume;
25 |
26 | Product() { // default constructor
27 | productID = 49;
28 | companyName = "EightSoft";
29 | modelName = "ZeroOne";
30 | isOn = false;
31 | volume = 8;
32 | }
33 |
34 | Product(int productID, String companyName, String modelName, boolean isOn, int volume) { // parametric constructor
35 | this.productID = productID;
36 | this.companyName = companyName;
37 | this.modelName = modelName;
38 | this.isOn = isOn;
39 | this.volume = volume;
40 | }
41 |
42 | public int getProductID() { return productID; } // returns product ID
43 |
44 | public String getCompanyName() { return companyName; } // returns company name
45 |
46 | public String getModelName() { return modelName; } // returns model name
47 |
48 | public int getVolume() { return volume; } // returns volume
49 |
50 | public void setProductID(int productID) { this.productID = productID; } // set product ID
51 |
52 | public void setCompanyName(String companyName) { this.companyName = companyName; } // set company name
53 |
54 | public void setModelName(String modelName) { this.modelName = modelName; } // set model name
55 |
56 | public void setVolume(int volume) {
57 | if (isOn && volume >= 0 && volume <=10) {
58 | this.volume = volume;
59 | System.out.println("\nVolume: " + getVolume());
60 | }
61 | else if (!isOn) {
62 | System.out.println("\nDevice is switched off!");
63 | }
64 | else {
65 | System.out.println("\nVolume must be in range (0-10)!");
66 | }
67 | }
68 |
69 | public void increaseVolume() { // increase volume of device
70 | if (isOn && volume>=0 && volume<=10) { // validation checking
71 | System.out.println("\nVolume: " + volume);
72 | volume++;
73 | }
74 | else if (!isOn) {
75 | System.out.println("\nDevice is switched off!");
76 | }
77 | else {
78 | System.out.println("\nVolume must be in range (0-10)!");
79 | }
80 | }
81 |
82 | public void decreaseVolume() { // decrease volume of device
83 | if (isOn && volume>=0 && volume<=10) { // validation checking
84 | System.out.println("\nVolume: " + volume);
85 | volume--;
86 | }
87 | else if (!isOn) {
88 | System.out.println("\nDevice is switched off!");
89 | }
90 | else {
91 | System.out.println("\nVolume must be in range (0-10)!");
92 | }
93 | }
94 |
95 | public void switchOn() {
96 | if (!isOn) {
97 | isOn = true;
98 | System.out.println("Device is switched on!");
99 | }
100 | else {
101 | System.out.println("\nDevice is already switched on!");
102 | }
103 | }
104 |
105 | public void switchOff() {
106 | if (isOn) {
107 | isOn = false;
108 | System.out.println("\nDevice is switched off!");
109 | }
110 | else {
111 | System.out.println("\nDevice is already switched off!");
112 | }
113 | }
114 | } // class
115 |
116 | // TV class inherited from Product class
117 | class TV extends Product {
118 | private int channel;
119 |
120 | TV() {
121 | switchOn();
122 | channel = 1;
123 | }
124 |
125 | public int getChannel() {
126 | return channel;
127 | }
128 |
129 | public void setChannel(int channel) {
130 | if (isOn && channel>=1 && channel<=100) {
131 | this.channel = channel;
132 | System.out.println("\nChannel: " + getChannel());
133 | }
134 | else if (!isOn) {
135 | System.out.println("\nDevice is switched off!");
136 | }
137 | else {
138 | System.out.println("\nChannels range must be (1-100)!");
139 | }
140 | }
141 |
142 | public void viewInfo() { // displying info
143 | System.out.println("\n*** TV info ***");
144 | System.out.println("Product ID: " + getProductID());
145 | System.out.println("Company name: " + getCompanyName());
146 | System.out.println("Model name: " + getModelName());
147 | System.out.println("Channel: " + getChannel());
148 | System.out.println("Volume: " + getVolume());
149 | System.out.println("isOn: " + isOn);
150 | }
151 | }
152 |
153 | class Mobile extends Product {
154 | int noOfSims;
155 |
156 | Mobile() {
157 | switchOn();
158 | noOfSims = 1; // set to default
159 | }
160 |
161 | public int getNoOfSims() { // get number of sims
162 | return noOfSims;
163 | }
164 |
165 | public void setNoOfSims(int noOfSims) { // set number of sims
166 | this.noOfSims = noOfSims;
167 | }
168 |
169 | // changing sim lots
170 | public void changeSim() {
171 | if (isOn && noOfSims==1 || noOfSims==2) {
172 | if (noOfSims==1) {
173 | System.out.println("\nYou have only one sim :)");
174 | }
175 | else {
176 | noOfSims++;
177 | System.out.println("\nSim no.: " + noOfSims);
178 | }
179 | }
180 | else {
181 | System.out.println("\nDevice is switched off!");
182 | }
183 | }
184 |
185 | public void viewInfo () { // viewing all info about the mobile
186 | System.out.println("\n*** Mobile info ***");
187 | System.out.println("Product ID: " + getProductID());
188 | System.out.println("Company name: " + getCompanyName());
189 | System.out.println("Model name: " + getModelName());
190 | System.out.println("Number of sims: " + getNoOfSims());
191 | System.out.println("Volume: " + getVolume());
192 | System.out.println("isOn: " + isOn);
193 | }
194 | }
195 |
196 | public class ProductDemo { // main class
197 | public static void main(String[] args) {
198 | Scanner input = new Scanner(System.in); // Create a Scanner object
199 | int option; // Initializing some variables
200 |
201 | Product product; // product reference
202 |
203 | for (int j=0; j<100; j++) { // for loop for reusing program
204 | System.out.println("\n***** MAIN MENU *****");
205 | System.out.println("1. TV");
206 | System.out.println("2. Mobile");
207 | System.out.println("0. Exit");
208 | System.out.print("Your choice: ");
209 | option = input.nextInt(); // get user option from above menu
210 |
211 | switch (option) { // main menu
212 | case 1:
213 | product = new TV();
214 | TV tv = (TV) product; // custing of objects
215 |
216 | for (int i=1; i<100; i++) {
217 | System.out.println("\n***** TV *****"); // menu for TV
218 | System.out.println("1. View info");
219 | System.out.println("2. Change product info");
220 | System.out.println("3. Switch channel");
221 | System.out.println("4. Increase volume");
222 | System.out.println("5. Decrease volume");
223 | System.out.println("6. Switch on");
224 | System.out.println("7. Switch off");
225 | System.out.println("0. Go back");
226 | System.out.print("Your choice: ");
227 |
228 | int optionTV = input.nextInt();
229 |
230 | switch (optionTV) {
231 | case 1:
232 | tv.viewInfo();
233 | break;
234 |
235 | case 2:
236 | // set product id
237 | int pid;
238 | System.out.print("Enter new product id: ");
239 | pid = input.nextInt();
240 | tv.setProductID(pid);
241 |
242 | // set company name
243 | String companyName;
244 | System.out.print("Enter new company name: ");
245 | companyName = input.next();
246 | tv.setCompanyName(companyName);
247 |
248 | // set model name
249 | String modelName;
250 | System.out.print("Enter new model name: ");
251 | modelName = input.next();
252 | tv.setModelName(modelName);
253 | break;
254 |
255 | case 3:
256 | // set channel
257 | int channel;
258 | if (tv.isOn) {
259 | System.out.print("Enter channel (1-100): ");
260 | channel = input.nextInt();
261 | tv.setChannel(channel);
262 | }
263 | else {
264 | System.out.println("\nDevice is switched off!");
265 | }
266 | break;
267 |
268 | case 4:
269 | tv.increaseVolume(); // increase volume
270 | break;
271 |
272 | case 5:
273 | tv.decreaseVolume(); // decrease volume
274 | break;
275 |
276 | case 6:
277 | tv.switchOn(); // switch on
278 | break;
279 |
280 | case 7:
281 | tv.switchOff(); // switch off
282 | break;
283 |
284 | case 0:
285 | i = 1000;
286 | break;
287 | }
288 | i--; // for validation loop
289 | }
290 | break;
291 |
292 | case 2:
293 | product = new Mobile(); // creating object of Mobile
294 | Mobile mobile = (Mobile) product; // custing of object
295 |
296 | for (int i=1; i<100; i++) {
297 | System.out.println("\n***** MOBILE *****"); // menu for mobile
298 | System.out.println("1. View info");
299 | System.out.println("2. Change product info");
300 | System.out.println("3. Switch sim");
301 | System.out.println("4. Increase volume");
302 | System.out.println("5. Decrease volume");
303 | System.out.println("6. Switch on");
304 | System.out.println("7. Switch off");
305 | System.out.println("0. Go back");
306 | System.out.print("Your choice: ");
307 |
308 | int optionMobile = input.nextInt();
309 |
310 | switch (optionMobile) {
311 | case 1:
312 | mobile.viewInfo();
313 | break;
314 |
315 | case 2:
316 | // set product id
317 | int pid;
318 | System.out.print("Enter new product id: ");
319 | pid = input.nextInt();
320 | mobile.setProductID(pid);
321 |
322 | // set company name
323 | String companyName;
324 | System.out.print("Enter new company name: ");
325 | companyName = input.next();
326 | mobile.setCompanyName(companyName);
327 |
328 | // set model name
329 | String modelName;
330 | System.out.print("Enter new model name: ");
331 | modelName = input.next();
332 | mobile.setModelName(modelName);
333 |
334 | // set number of sims
335 | int noOfSims;
336 | System.out.print("Enter number of sims (1-2): ");
337 | noOfSims = input.nextInt(); //setNoOfSims
338 | if (noOfSims==1 || noOfSims==2) {
339 | mobile.setNoOfSims(noOfSims);
340 | }
341 | else {
342 | System.out.print("Wrong! Number could be 1 or 2!");
343 | }
344 | break;
345 |
346 | case 3:
347 | mobile.changeSim();
348 | break;
349 |
350 | case 4:
351 | mobile.increaseVolume();
352 | break;
353 |
354 | case 5:
355 | mobile.decreaseVolume();
356 | break;
357 |
358 | case 6:
359 | mobile.switchOn();
360 | break;
361 |
362 | case 7:
363 | mobile.switchOff();
364 | break;
365 |
366 | case 0:
367 | i = 1000;
368 | break;
369 | }
370 | i--; // for validating loop
371 | }
372 | break;
373 |
374 | case 0:
375 | System.out.println("Quitting Program...");
376 | System.exit(0); // program ends
377 | break;
378 |
379 | default:
380 | System.out.println("Please enter a valid option!");
381 | } // End of switch
382 | j--;
383 | } // end of for
384 | } // end of main()
385 | } // end of ProductDemo
386 |
--------------------------------------------------------------------------------