Java Assignment Codes
VerifiedAdded on  2023/05/30
|52
|5341
|240
AI Summary
Get Java assignment codes for Counter, Traffic Lights and Hilbert Curves. Learn Java programming with Desklib's online library for study material with solved assignments, essays, dissertation etc.
Contribute Materials
Your contribution can guide someone’s learning journey. Share your
documents today.
Running head: Java Assignment Codes 1
Java Assignment Codes
Student Name
Institution
Location of Institution
Professor’s Name
Date
Java Assignment Codes
Student Name
Institution
Location of Institution
Professor’s Name
Date
Secure Best Marks with AI Grader
Need help grading? Try our AI Grader for instant feedback on your assignments.
Java Assignment Codes 2
Table of Contents
1.1 Question One Part One..............................................................................................................3
1.2 Question One Part Two.............................................................................................................7
1.3 Question Two...........................................................................................................................11
1.4 Question Three.........................................................................................................................19
1.4.1 Main Class........................................................................................................................19
1.4.2 Applet...............................................................................................................................27
1.5 Question Four..........................................................................................................................28
1.5.1 Morse Code Client............................................................................................................28
1.5.2 Morse Code Server...........................................................................................................44
Table of Contents
1.1 Question One Part One..............................................................................................................3
1.2 Question One Part Two.............................................................................................................7
1.3 Question Two...........................................................................................................................11
1.4 Question Three.........................................................................................................................19
1.4.1 Main Class........................................................................................................................19
1.4.2 Applet...............................................................................................................................27
1.5 Question Four..........................................................................................................................28
1.5.1 Morse Code Client............................................................................................................28
1.5.2 Morse Code Server...........................................................................................................44
Java Assignment Codes 3
1.1 Question One Part One
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package counter;
import java.util.ArrayList;
import java.util.Scanner;
/**
*
* @author Keeprawteach
*/
public class Counter {
/**
* @param args the command line arguments
*/
int k, m, counter, sum_counter;
1.1 Question One Part One
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package counter;
import java.util.ArrayList;
import java.util.Scanner;
/**
*
* @author Keeprawteach
*/
public class Counter {
/**
* @param args the command line arguments
*/
int k, m, counter, sum_counter;
Java Assignment Codes 4
public Counter() {
Scanner in = new Scanner(System.in);
System.out.println("Enter number: ");
int x = in.nextInt();
DoCalculations(x);
}
void DoCalculations(int n) {
System.out.println("Counter Sum Counter| n | m");
ArrayList<String> combs = new ArrayList<>();
counter = 0;
sum_counter = 0;
for (k = 1; k < n; k++) {
for (m = k + 1; m <= n; m++) {
counter++;
if ((k + m) == n) {
combs.add(k + " + " + m + " = " + n);
}
public Counter() {
Scanner in = new Scanner(System.in);
System.out.println("Enter number: ");
int x = in.nextInt();
DoCalculations(x);
}
void DoCalculations(int n) {
System.out.println("Counter Sum Counter| n | m");
ArrayList<String> combs = new ArrayList<>();
counter = 0;
sum_counter = 0;
for (k = 1; k < n; k++) {
for (m = k + 1; m <= n; m++) {
counter++;
if ((k + m) == n) {
combs.add(k + " + " + m + " = " + n);
}
Secure Best Marks with AI Grader
Need help grading? Try our AI Grader for instant feedback on your assignments.
Java Assignment Codes 5
if ((k + m) == n) {
sum_counter++;
System.out.println(" " + counter + " " + sum_counter + " " + k + "
" + m);
}else{
System.out.println(" " + counter + " " + k + " " + m);
}
}
}
System.out.println (
"\n\n");
System.out.println (
"Total Combinations: " + String.valueOf(combs.size()));
System.out.println (
"\n\nCombinations:\n");
if (!combs.isEmpty ()
if ((k + m) == n) {
sum_counter++;
System.out.println(" " + counter + " " + sum_counter + " " + k + "
" + m);
}else{
System.out.println(" " + counter + " " + k + " " + m);
}
}
}
System.out.println (
"\n\n");
System.out.println (
"Total Combinations: " + String.valueOf(combs.size()));
System.out.println (
"\n\nCombinations:\n");
if (!combs.isEmpty ()
Java Assignment Codes 6
) {
for (String comb : combs) {
System.out.println(comb);
}
}
}
public static void main(String[] args) {
// TODO code application logic here
new Counter();
}
}
) {
for (String comb : combs) {
System.out.println(comb);
}
}
}
public static void main(String[] args) {
// TODO code application logic here
new Counter();
}
}
Java Assignment Codes 7
1.2 Question One Part Two
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package counter.part.two;
import java.util.ArrayList;
import java.util.Scanner;
/**
*
* @author Keeprawteach
*/
public class CounterPartTwo {
/**
* @param args the command line arguments
*/
int a, b, c, d, e, f, counter, sum_counter;
1.2 Question One Part Two
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package counter.part.two;
import java.util.ArrayList;
import java.util.Scanner;
/**
*
* @author Keeprawteach
*/
public class CounterPartTwo {
/**
* @param args the command line arguments
*/
int a, b, c, d, e, f, counter, sum_counter;
Paraphrase This Document
Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Java Assignment Codes 8
public CounterPartTwo() {
Scanner in = new Scanner(System.in);
System.out.println("Enter number: ");
int x = in.nextInt();
DoCalculations(x);
}
public static void main(String[] args) {
// TODO code application logic here
new CounterPartTwo();
}
private void DoCalculations(int n) {
System.out.println("Counter | Sum Counter | a | b | c | d | e | f ");
ArrayList<String> combs = new ArrayList<>();
counter = 0;
sum_counter = 0;
for (a = 1; a < n; a++) {
for (b = a + 1; b <= n; b++) {
public CounterPartTwo() {
Scanner in = new Scanner(System.in);
System.out.println("Enter number: ");
int x = in.nextInt();
DoCalculations(x);
}
public static void main(String[] args) {
// TODO code application logic here
new CounterPartTwo();
}
private void DoCalculations(int n) {
System.out.println("Counter | Sum Counter | a | b | c | d | e | f ");
ArrayList<String> combs = new ArrayList<>();
counter = 0;
sum_counter = 0;
for (a = 1; a < n; a++) {
for (b = a + 1; b <= n; b++) {
Java Assignment Codes 9
for (c = b + 1; b <= n; b++) {
for (d = c + 1; b <= n; b++) {
for (e = d + 1; b <= n; b++) {
for (f = e + 1; b <= n; b++) {
counter++;
if ((a + b + c + d + e + f) == n) {
combs.add(a + " + " + b + " + " + c + " + " + d + " + " + e + " + " + f + " =
" + n);
}
if ((a + b + c + d + e + f) == n) {
sum_counter++;
System.out.println(counter +" "+sum_counter+" "+a+" "+b+"
"+c+" "+d+" "+e+" "+f );
} else {
System.out.println(counter +" "+a+" "+b+" "+c+" "+d+"
"+e+" "+f );
}
}
}
for (c = b + 1; b <= n; b++) {
for (d = c + 1; b <= n; b++) {
for (e = d + 1; b <= n; b++) {
for (f = e + 1; b <= n; b++) {
counter++;
if ((a + b + c + d + e + f) == n) {
combs.add(a + " + " + b + " + " + c + " + " + d + " + " + e + " + " + f + " =
" + n);
}
if ((a + b + c + d + e + f) == n) {
sum_counter++;
System.out.println(counter +" "+sum_counter+" "+a+" "+b+"
"+c+" "+d+" "+e+" "+f );
} else {
System.out.println(counter +" "+a+" "+b+" "+c+" "+d+"
"+e+" "+f );
}
}
}
Java Assignment Codes 10
}
}
}
}
System.out.println("\n\n");
System.out.println("Total Combinations: " + String.valueOf(combs.size()));
System.out.println("\n\nCombinations:\n");
if (!combs.isEmpty()) {
for (String comb : combs) {
System.out.println(comb);
}
}
}
}
}
}
}
}
System.out.println("\n\n");
System.out.println("Total Combinations: " + String.valueOf(combs.size()));
System.out.println("\n\nCombinations:\n");
if (!combs.isEmpty()) {
for (String comb : combs) {
System.out.println(comb);
}
}
}
}
Secure Best Marks with AI Grader
Need help grading? Try our AI Grader for instant feedback on your assignments.
Java Assignment Codes 11
1.3 Question Two
package traffic.lights;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class TrafficLights extends JFrame implements ItemListener{
/**
*
*/
private static final long serial_number_version = 1L;
1.3 Question Two
package traffic.lights;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class TrafficLights extends JFrame implements ItemListener{
/**
*
*/
private static final long serial_number_version = 1L;
Java Assignment Codes 12
//Create buttons for traffic Lights_of_Traffics
private JRadioButton Red_Radio_Button;
private JRadioButton Yellow_Radio_Button;
private JRadioButton Green_Radio_Button;
private ButtonGroup Overal_Radio_Button = new ButtonGroup();
//create class Lights_of_Traffics
private TrafficLights.Light Lights_of_Traffics = new TrafficLights.Light();
public static void main(String[] args)
{
//Create frame
TrafficLights frame = new TrafficLights();
frame.setDefaultCloseOperation(3);
frame.setSize(400, 170);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public TrafficLights()
{
//Create buttons for traffic Lights_of_Traffics
private JRadioButton Red_Radio_Button;
private JRadioButton Yellow_Radio_Button;
private JRadioButton Green_Radio_Button;
private ButtonGroup Overal_Radio_Button = new ButtonGroup();
//create class Lights_of_Traffics
private TrafficLights.Light Lights_of_Traffics = new TrafficLights.Light();
public static void main(String[] args)
{
//Create frame
TrafficLights frame = new TrafficLights();
frame.setDefaultCloseOperation(3);
frame.setSize(400, 170);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public TrafficLights()
{
Java Assignment Codes 13
setTitle("Traffic Lights");
JPanel p1 = new JPanel();
p1.setLayout(new FlowLayout(1));
p1.add(this.Lights_of_Traffics);
JPanel p2 = new JPanel();
p2.setLayout(new FlowLayout());
p2.add(this.Red_Radio_Button = new JRadioButton("Red"));
p2.add(this.Yellow_Radio_Button = new JRadioButton("Yellow"));
p2.add(this.Green_Radio_Button = new JRadioButton("Green"));
this.Red_Radio_Button.setMnemonic('R');
this.Yellow_Radio_Button.setMnemonic('Y');
this.Green_Radio_Button.setMnemonic('G');
this.Overal_Radio_Button.add(this.Red_Radio_Button);
this.Overal_Radio_Button.add(this.Yellow_Radio_Button);
this.Overal_Radio_Button.add(this.Green_Radio_Button);
setTitle("Traffic Lights");
JPanel p1 = new JPanel();
p1.setLayout(new FlowLayout(1));
p1.add(this.Lights_of_Traffics);
JPanel p2 = new JPanel();
p2.setLayout(new FlowLayout());
p2.add(this.Red_Radio_Button = new JRadioButton("Red"));
p2.add(this.Yellow_Radio_Button = new JRadioButton("Yellow"));
p2.add(this.Green_Radio_Button = new JRadioButton("Green"));
this.Red_Radio_Button.setMnemonic('R');
this.Yellow_Radio_Button.setMnemonic('Y');
this.Green_Radio_Button.setMnemonic('G');
this.Overal_Radio_Button.add(this.Red_Radio_Button);
this.Overal_Radio_Button.add(this.Yellow_Radio_Button);
this.Overal_Radio_Button.add(this.Green_Radio_Button);
Paraphrase This Document
Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Java Assignment Codes 14
setLayout(new BorderLayout());
add(p1, "Center");
add(p2, "South");
this.Red_Radio_Button.addItemListener(this);
this.Yellow_Radio_Button.addItemListener(this);
this.Green_Radio_Button.addItemListener(this);
this.Green_Radio_Button.setSelected(true);
this.Lights_of_Traffics.turnOnGreen();
}
public void itemStateChanged(ItemEvent e)
{
if (this.Red_Radio_Button.isSelected()) {
this.Lights_of_Traffics.turnOnRed();
}
if (this.Yellow_Radio_Button.isSelected()) {
this.Lights_of_Traffics.turnOnYellow();
}
if (this.Green_Radio_Button.isSelected())
this.Lights_of_Traffics.turnOnGreen();
}
setLayout(new BorderLayout());
add(p1, "Center");
add(p2, "South");
this.Red_Radio_Button.addItemListener(this);
this.Yellow_Radio_Button.addItemListener(this);
this.Green_Radio_Button.addItemListener(this);
this.Green_Radio_Button.setSelected(true);
this.Lights_of_Traffics.turnOnGreen();
}
public void itemStateChanged(ItemEvent e)
{
if (this.Red_Radio_Button.isSelected()) {
this.Lights_of_Traffics.turnOnRed();
}
if (this.Yellow_Radio_Button.isSelected()) {
this.Lights_of_Traffics.turnOnYellow();
}
if (this.Green_Radio_Button.isSelected())
this.Lights_of_Traffics.turnOnGreen();
}
Java Assignment Codes 15
class Light extends JPanel
{
/**
*
*/
private static final long serializer = 1L;
private boolean red_color;
private boolean yellow_color;
private boolean green_color;
public Light() {
}
public void turnOnRed() {
this.red_color = true;
this.yellow_color = false;
this.green_color = false;
repaint();
}
public void turnOnYellow()
class Light extends JPanel
{
/**
*
*/
private static final long serializer = 1L;
private boolean red_color;
private boolean yellow_color;
private boolean green_color;
public Light() {
}
public void turnOnRed() {
this.red_color = true;
this.yellow_color = false;
this.green_color = false;
repaint();
}
public void turnOnYellow()
Java Assignment Codes 16
{
this.red_color = false;
this.yellow_color = true;
this.green_color = false;
repaint();
}
public void turnOnGreen()
{
this.red_color = false;
this.yellow_color = false;
this.green_color = true;
repaint();
}
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
{
this.red_color = false;
this.yellow_color = true;
this.green_color = false;
repaint();
}
public void turnOnGreen()
{
this.red_color = false;
this.yellow_color = false;
this.green_color = true;
repaint();
}
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
Secure Best Marks with AI Grader
Need help grading? Try our AI Grader for instant feedback on your assignments.
Java Assignment Codes 17
if (this.red_color) {
g.setColor(Color.red);
g.fillOval(10, 10, 20, 20);
g.setColor(Color.black);
g.drawOval(10, 35, 20, 20);
g.drawOval(10, 60, 20, 20);
g.drawRect(5, 5, 30, 80);
}
else if (this.yellow_color) {
g.setColor(Color.yellow);
g.fillOval(10, 35, 20, 20);
g.setColor(Color.black);
g.drawRect(5, 5, 30, 80);
g.drawOval(10, 10, 20, 20);
g.drawOval(10, 60, 20, 20);
}
else if (this.green_color) {
g.setColor(Color.green);
g.fillOval(10, 60, 20, 20);
g.setColor(Color.black);
g.drawRect(5, 5, 30, 80);
if (this.red_color) {
g.setColor(Color.red);
g.fillOval(10, 10, 20, 20);
g.setColor(Color.black);
g.drawOval(10, 35, 20, 20);
g.drawOval(10, 60, 20, 20);
g.drawRect(5, 5, 30, 80);
}
else if (this.yellow_color) {
g.setColor(Color.yellow);
g.fillOval(10, 35, 20, 20);
g.setColor(Color.black);
g.drawRect(5, 5, 30, 80);
g.drawOval(10, 10, 20, 20);
g.drawOval(10, 60, 20, 20);
}
else if (this.green_color) {
g.setColor(Color.green);
g.fillOval(10, 60, 20, 20);
g.setColor(Color.black);
g.drawRect(5, 5, 30, 80);
Java Assignment Codes 18
g.drawOval(10, 10, 20, 20);
g.drawOval(10, 35, 20, 20);
}
else {
g.setColor(Color.black);
g.drawRect(5, 5, 30, 80);
g.drawOval(10, 10, 20, 20);
g.drawOval(10, 35, 20, 20);
g.drawOval(10, 60, 20, 20);
}
}
public Dimension getPreferredSize()
{
return new Dimension(40, 90);
}
}
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
g.drawOval(10, 10, 20, 20);
g.drawOval(10, 35, 20, 20);
}
else {
g.setColor(Color.black);
g.drawRect(5, 5, 30, 80);
g.drawOval(10, 10, 20, 20);
g.drawOval(10, 35, 20, 20);
g.drawOval(10, 60, 20, 20);
}
}
public Dimension getPreferredSize()
{
return new Dimension(40, 90);
}
}
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
Java Assignment Codes 19
1.4 Question Three
1.4.1 Main Class
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package hilbert.curve;
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
1.4 Question Three
1.4.1 Main Class
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package hilbert.curve;
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
Paraphrase This Document
Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Java Assignment Codes 20
/**
*
* @author Keeprawteach
*/
public class HilbertCurves extends JApplet {
/**
* @param args the command line arguments
*/
private JTextField OrderTextfield = new JTextField("0", 5);
private HilbertCurve hilbertCurvePanel = new HilbertCurve();
public HilbertCurves() {
JPanel panel = new JPanel();
panel.add(new JLabel("Enter an Order"));
panel.add(OrderTextfield);
/**
*
* @author Keeprawteach
*/
public class HilbertCurves extends JApplet {
/**
* @param args the command line arguments
*/
private JTextField OrderTextfield = new JTextField("0", 5);
private HilbertCurve hilbertCurvePanel = new HilbertCurve();
public HilbertCurves() {
JPanel panel = new JPanel();
panel.add(new JLabel("Enter an Order"));
panel.add(OrderTextfield);
Java Assignment Codes 21
OrderTextfield.setHorizontalAlignment(SwingConstants.RIGHT);
add(hilbertCurvePanel);
add(panel, BorderLayout.SOUTH);
OrderTextfield.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
hilbertCurvePanel.setOrder(Integer.parseInt(OrderTextfield.getText()));
}
});
}
private static class HilbertCurve extends JPanel {
private int lenght;
private int order = 1;
private int a, b;
private void setOrder(int order) {
this.order = order;
repaint();
OrderTextfield.setHorizontalAlignment(SwingConstants.RIGHT);
add(hilbertCurvePanel);
add(panel, BorderLayout.SOUTH);
OrderTextfield.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
hilbertCurvePanel.setOrder(Integer.parseInt(OrderTextfield.getText()));
}
});
}
private static class HilbertCurve extends JPanel {
private int lenght;
private int order = 1;
private int a, b;
private void setOrder(int order) {
this.order = order;
repaint();
Java Assignment Codes 22
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
lenght = Math.min(getWidth(), getHeight());
for (int i = 0; i < order; i++) {
lenght /= 2;
a = lenght / 2;
b = lenght / 2;
Upper(g, order);
}
}
private void Upper(Graphics g, int order) {
if (order > 0) {
Left(g, order - 1);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
lenght = Math.min(getWidth(), getHeight());
for (int i = 0; i < order; i++) {
lenght /= 2;
a = lenght / 2;
b = lenght / 2;
Upper(g, order);
}
}
private void Upper(Graphics g, int order) {
if (order > 0) {
Left(g, order - 1);
Secure Best Marks with AI Grader
Need help grading? Try our AI Grader for instant feedback on your assignments.
Java Assignment Codes 23
lineNewPosition(g, 0, lenght);
Upper(g, order - 1);
lineNewPosition(g, lenght, 0);
Upper(g, order - 1);
lineNewPosition(g, 0, -lenght);
right(g, order - 1);
}
}
private void Left(Graphics g, int order) {
if (order > 0) {
Upper(g, order - 1);
lineNewPosition(g, lenght, 0);
Left(g, order - 1);
lineNewPosition(g, 0, lenght);
Left(g, order - 1);
lineNewPosition(g, -lenght, 0);
Down(g, order - 1);
lineNewPosition(g, 0, lenght);
Upper(g, order - 1);
lineNewPosition(g, lenght, 0);
Upper(g, order - 1);
lineNewPosition(g, 0, -lenght);
right(g, order - 1);
}
}
private void Left(Graphics g, int order) {
if (order > 0) {
Upper(g, order - 1);
lineNewPosition(g, lenght, 0);
Left(g, order - 1);
lineNewPosition(g, 0, lenght);
Left(g, order - 1);
lineNewPosition(g, -lenght, 0);
Down(g, order - 1);
Java Assignment Codes 24
}
}
private void right(Graphics g, int order) {
if (order > 0) {
Down(g, order - 1);
lineNewPosition(g, -lenght, 0);
right(g, order - 1);
lineNewPosition(g, 0, -lenght);
right(g, order - 1);
lineNewPosition(g, lenght, 0);
Upper(g, order - 1);
}
}
private void Down(Graphics g, int order) {
if (order > 0) {
}
}
private void right(Graphics g, int order) {
if (order > 0) {
Down(g, order - 1);
lineNewPosition(g, -lenght, 0);
right(g, order - 1);
lineNewPosition(g, 0, -lenght);
right(g, order - 1);
lineNewPosition(g, lenght, 0);
Upper(g, order - 1);
}
}
private void Down(Graphics g, int order) {
if (order > 0) {
Java Assignment Codes 25
right(g, order - 1);
lineNewPosition(g, 0, -lenght);
Down(g, order - 1);
lineNewPosition(g, -lenght, 0);
Down(g, order - 1);
lineNewPosition(g, 0, lenght);
Left(g, order - 1);
}
}
private void lineNewPosition(Graphics g, int deltaX, int deltaY) {
g.drawLine(a, b, a + deltaX, b + deltaY);
a += deltaX;
b += deltaY;
}
}
right(g, order - 1);
lineNewPosition(g, 0, -lenght);
Down(g, order - 1);
lineNewPosition(g, -lenght, 0);
Down(g, order - 1);
lineNewPosition(g, 0, lenght);
Left(g, order - 1);
}
}
private void lineNewPosition(Graphics g, int deltaX, int deltaY) {
g.drawLine(a, b, a + deltaX, b + deltaY);
a += deltaX;
b += deltaY;
}
}
Paraphrase This Document
Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Java Assignment Codes 26
public static void main(String[] args) {
// TODO code application logic here
JApplet applet = new HilbertCurves();
applet.init();
applet.start();
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Hilbert Curves");
frame.getContentPane().add(applet, BorderLayout.CENTER);
frame.setSize(512, 512);
frame.setVisible(true);
}
}
public static void main(String[] args) {
// TODO code application logic here
JApplet applet = new HilbertCurves();
applet.init();
applet.start();
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Hilbert Curves");
frame.getContentPane().add(applet, BorderLayout.CENTER);
frame.setSize(512, 512);
frame.setVisible(true);
}
}
Java Assignment Codes 27
1.4.2 Applet
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
</head>
<body>
<applet code="HilbertCurves.class" width="250" height="50"></applet>
</body>
</html>
1.4.2 Applet
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
</head>
<body>
<applet code="HilbertCurves.class" width="250" height="50"></applet>
</body>
</html>
Java Assignment Codes 28
1.5 Question Four
1.5.1 Morse Code Client
package NetworkedMorseCode_client;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Map;
import java.util.TreeMap;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
1.5 Question Four
1.5.1 Morse Code Client
package NetworkedMorseCode_client;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Map;
import java.util.TreeMap;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
Secure Best Marks with AI Grader
Need help grading? Try our AI Grader for instant feedback on your assignments.
Java Assignment Codes 29
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
/*
@author Keeprawteach
*/
public class ClientTest {
public static void main(String[] args) {
ClientApp application;
if (args.length == 0) {
application = new ClientApp("127.0.0.1");
} else {
application = new ClientApp(args[0]);
}
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
application.setResizable(false);
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
/*
@author Keeprawteach
*/
public class ClientTest {
public static void main(String[] args) {
ClientApp application;
if (args.length == 0) {
application = new ClientApp("127.0.0.1");
} else {
application = new ClientApp(args[0]);
}
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
application.setResizable(false);
Java Assignment Codes 30
application.runClient();
}
private static class ClientApp extends JFrame {
private JTextField enterField;
private JTextArea displayArea;
private JTextArea notificationArea;
private JScrollPane notices;
private ObjectOutputStream output;
private ObjectInputStream input;
private String message = "";
private String chatServer;
private String name = "";
private Socket client;
private Boolean openConnection;
final private Character[] characters = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '.',
',', ':', '?', '\'', '-', '/', '"', '@', '='};
application.runClient();
}
private static class ClientApp extends JFrame {
private JTextField enterField;
private JTextArea displayArea;
private JTextArea notificationArea;
private JScrollPane notices;
private ObjectOutputStream output;
private ObjectInputStream input;
private String message = "";
private String chatServer;
private String name = "";
private Socket client;
private Boolean openConnection;
final private Character[] characters = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '.',
',', ':', '?', '\'', '-', '/', '"', '@', '='};
Java Assignment Codes 31
final private String[] codes = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.",
"....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-",
".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", ".----",
"..---", "...--", "....-", ".....", "-....", "--...", "---..", "----.",
"-----", ".-.-.-", "--..--", "---...", "..--..", ".----.", "-....-", "-..-.",
".-..-.", ".--.-.", "-...-"};
private Map<Character, String> encodeMorse;
private Map<String, Character> decodeMorse;
public ClientApp(String host) {
super("Happiness Enchancer 2.0");
chatServer = host;
while ((name.length() == 0) || (name.replace(" ", "").length() == 0)) {
name = JOptionPane.showInputDialog("Please enter your display name:");
}
enterField = new JTextField();
enterField.setEditable(false);
enterField.addActionListener(
new ActionListener() {
final private String[] codes = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.",
"....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-",
".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", ".----",
"..---", "...--", "....-", ".....", "-....", "--...", "---..", "----.",
"-----", ".-.-.-", "--..--", "---...", "..--..", ".----.", "-....-", "-..-.",
".-..-.", ".--.-.", "-...-"};
private Map<Character, String> encodeMorse;
private Map<String, Character> decodeMorse;
public ClientApp(String host) {
super("Happiness Enchancer 2.0");
chatServer = host;
while ((name.length() == 0) || (name.replace(" ", "").length() == 0)) {
name = JOptionPane.showInputDialog("Please enter your display name:");
}
enterField = new JTextField();
enterField.setEditable(false);
enterField.addActionListener(
new ActionListener() {
Paraphrase This Document
Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Java Assignment Codes 32
public void actionPerformed(ActionEvent event) {
if (event.getActionCommand().equalsIgnoreCase("terminate")) {
sendData("\\quit");
openConnection = false;
} else {
sendData(convertToMorse(event.getActionCommand()));
}
enterField.setText("");
}
}
);
this.addWindowListener(
new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
if (openConnection) {
public void actionPerformed(ActionEvent event) {
if (event.getActionCommand().equalsIgnoreCase("terminate")) {
sendData("\\quit");
openConnection = false;
} else {
sendData(convertToMorse(event.getActionCommand()));
}
enterField.setText("");
}
}
);
this.addWindowListener(
new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
if (openConnection) {
Java Assignment Codes 33
sendData("\\quit");
openConnection = false;
}
dispose();
System.exit(1);
}
}
);
}
}
);
add(enterField, BorderLayout.NORTH);
displayArea = new JTextArea();
displayArea.setEditable(false);
add(new JScrollPane(displayArea), BorderLayout.CENTER);
notificationArea = new JTextArea();
notificationArea.setEditable(false);
notificationArea.setBackground(Color.LIGHT_GRAY);
sendData("\\quit");
openConnection = false;
}
dispose();
System.exit(1);
}
}
);
}
}
);
add(enterField, BorderLayout.NORTH);
displayArea = new JTextArea();
displayArea.setEditable(false);
add(new JScrollPane(displayArea), BorderLayout.CENTER);
notificationArea = new JTextArea();
notificationArea.setEditable(false);
notificationArea.setBackground(Color.LIGHT_GRAY);
Java Assignment Codes 34
notificationArea.setForeground(Color.DARK_GRAY);
notices = new JScrollPane(notificationArea);
notices.setPreferredSize(new Dimension(800, 150));
add(notices, BorderLayout.SOUTH);
setSize(800, 600);
setVisible(true);
openConnection = true;
encodeMorse = new TreeMap<>();
decodeMorse = new TreeMap<>();
for (int i = 0; i < characters.length; i++) {
encodeMorse.put(characters[i], codes[i]);
decodeMorse.put(codes[i], characters[i]);
}
}
public void runClient() {
Boolean socketConnected = false;
try {
notificationArea.setForeground(Color.DARK_GRAY);
notices = new JScrollPane(notificationArea);
notices.setPreferredSize(new Dimension(800, 150));
add(notices, BorderLayout.SOUTH);
setSize(800, 600);
setVisible(true);
openConnection = true;
encodeMorse = new TreeMap<>();
decodeMorse = new TreeMap<>();
for (int i = 0; i < characters.length; i++) {
encodeMorse.put(characters[i], codes[i]);
decodeMorse.put(codes[i], characters[i]);
}
}
public void runClient() {
Boolean socketConnected = false;
try {
Secure Best Marks with AI Grader
Need help grading? Try our AI Grader for instant feedback on your assignments.
Java Assignment Codes 35
if (socketConnected = connectToServer()) {
getStreams();
processConnection();
}
} catch (EOFException eofException) {
displayNotice("Client terminated connection");
} catch (IOException ioException) {
ioException.printStackTrace();
} finally {
if (socketConnected) {
closeConnection();
}
}
}
private boolean connectToServer() throws IOException {
displayNotice("Welcome " + name + "!");
try {
if (socketConnected = connectToServer()) {
getStreams();
processConnection();
}
} catch (EOFException eofException) {
displayNotice("Client terminated connection");
} catch (IOException ioException) {
ioException.printStackTrace();
} finally {
if (socketConnected) {
closeConnection();
}
}
}
private boolean connectToServer() throws IOException {
displayNotice("Welcome " + name + "!");
try {
Java Assignment Codes 36
client = new Socket(InetAddress.getByName(chatServer), 61000);
} catch (IOException e) {
displayNotice("Server connection could not be established");
return false;
}
displayNotice("Connected to: " + client.getInetAddress().getHostName());
return true;
}
private void getStreams() throws IOException {
output = new ObjectOutputStream(client.getOutputStream());
output.writeObject(name);
output.flush();
input = new ObjectInputStream(client.getInputStream());
displayNotice("Got I/O streams");
}
client = new Socket(InetAddress.getByName(chatServer), 61000);
} catch (IOException e) {
displayNotice("Server connection could not be established");
return false;
}
displayNotice("Connected to: " + client.getInetAddress().getHostName());
return true;
}
private void getStreams() throws IOException {
output = new ObjectOutputStream(client.getOutputStream());
output.writeObject(name);
output.flush();
input = new ObjectInputStream(client.getInputStream());
displayNotice("Got I/O streams");
}
Java Assignment Codes 37
private void processConnection() throws IOException {
setTextFieldEditable(true);
int newLine;
while (openConnection) {
try {
message = (String) input.readObject();
newLine = message.indexOf('\n');
displayMessage(message.substring(0, newLine));
displayMessage(" " + convertToText(message.substring(newLine + 1)));
} catch (ClassNotFoundException classNotFoundException) {
displayNotice("Unknown object type received");
}
}
}
private void processConnection() throws IOException {
setTextFieldEditable(true);
int newLine;
while (openConnection) {
try {
message = (String) input.readObject();
newLine = message.indexOf('\n');
displayMessage(message.substring(0, newLine));
displayMessage(" " + convertToText(message.substring(newLine + 1)));
} catch (ClassNotFoundException classNotFoundException) {
displayNotice("Unknown object type received");
}
}
}
Paraphrase This Document
Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Java Assignment Codes 38
private void closeConnection() {
displayNotice("Closing connection");
setTextFieldEditable(false);
try {
output.close();
input.close();
client.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
private void sendData(String message) {
try {
output.writeObject(message);
output.flush();
} catch (IOException ioException) {
displayNotice("Error writing object");
}
private void closeConnection() {
displayNotice("Closing connection");
setTextFieldEditable(false);
try {
output.close();
input.close();
client.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
private void sendData(String message) {
try {
output.writeObject(message);
output.flush();
} catch (IOException ioException) {
displayNotice("Error writing object");
}
Java Assignment Codes 39
}
private void displayMessage(final String messageToDisplay) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
displayArea.append(messageToDisplay + "\n");
}
}
);
}
private void displayNotice(final String messageToDisplay) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
notificationArea.append(messageToDisplay + "\n");
}
}
);
}
}
private void displayMessage(final String messageToDisplay) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
displayArea.append(messageToDisplay + "\n");
}
}
);
}
private void displayNotice(final String messageToDisplay) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
notificationArea.append(messageToDisplay + "\n");
}
}
);
}
Java Assignment Codes 40
private void setTextFieldEditable(final boolean editable) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
enterField.setEditable(editable);
}
}
);
}
private String convertToMorse(String encodeMessage) {
String[] tempWords = encodeMessage.split(" ");
Character tempChar;
StringBuilder codedString = new StringBuilder();
for (String token : tempWords) {
for (int i = 0; i < token.length(); i++) {
tempChar = Character.toLowerCase(token.charAt(i));
private void setTextFieldEditable(final boolean editable) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
enterField.setEditable(editable);
}
}
);
}
private String convertToMorse(String encodeMessage) {
String[] tempWords = encodeMessage.split(" ");
Character tempChar;
StringBuilder codedString = new StringBuilder();
for (String token : tempWords) {
for (int i = 0; i < token.length(); i++) {
tempChar = Character.toLowerCase(token.charAt(i));
Secure Best Marks with AI Grader
Need help grading? Try our AI Grader for instant feedback on your assignments.
Java Assignment Codes 41
if (encodeMorse.containsKey(tempChar)) {
codedString.append(encodeMorse.get(tempChar));
} else {
codedString.append(token.charAt(i));
}
if (i != (token.length() - 1)) {
codedString.append('/');
}
}
codedString.append("//");
}
displayNotice(" Your Encoded Message is:\n "
+ codedString.toString() + "\n");
return codedString.toString();
}
private String convertToText(String decodeMessage) {
if (encodeMorse.containsKey(tempChar)) {
codedString.append(encodeMorse.get(tempChar));
} else {
codedString.append(token.charAt(i));
}
if (i != (token.length() - 1)) {
codedString.append('/');
}
}
codedString.append("//");
}
displayNotice(" Your Encoded Message is:\n "
+ codedString.toString() + "\n");
return codedString.toString();
}
private String convertToText(String decodeMessage) {
Java Assignment Codes 42
String[] tempWords = decodeMessage.split("//");
String[] tempString;
StringBuilder decodedString = new StringBuilder();
Boolean capNext = true;
for (String token : tempWords) {
tempString = token.split("/");
for (String code : tempString) {
if (decodeMorse.containsKey(code)) {
if (capNext) {
decodedString.append(Character.toUpperCase(decodeMorse.get(code)));
capNext = false;
} else {
decodedString.append(decodeMorse.get(code));
}
if (code.equals(".-.-.-") || code.equals("..--..") || code.equals('!')) {
capNext = true;
}
} else {
decodedString.append(code);
String[] tempWords = decodeMessage.split("//");
String[] tempString;
StringBuilder decodedString = new StringBuilder();
Boolean capNext = true;
for (String token : tempWords) {
tempString = token.split("/");
for (String code : tempString) {
if (decodeMorse.containsKey(code)) {
if (capNext) {
decodedString.append(Character.toUpperCase(decodeMorse.get(code)));
capNext = false;
} else {
decodedString.append(decodeMorse.get(code));
}
if (code.equals(".-.-.-") || code.equals("..--..") || code.equals('!')) {
capNext = true;
}
} else {
decodedString.append(code);
Java Assignment Codes 43
}
}
decodedString.append(" ");
}
return decodedString.toString();
}
}
}
}
}
decodedString.append(" ");
}
return decodedString.toString();
}
}
}
Paraphrase This Document
Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Java Assignment Codes 44
1.5.2 Morse Code Server
package NetworkedMorseCode_server;
import java.awt.BorderLayout;
import java.awt.Color;
import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
1.5.2 Morse Code Server
package NetworkedMorseCode_server;
import java.awt.BorderLayout;
import java.awt.Color;
import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
Java Assignment Codes 45
public class ServerTest
{
public static void main( String[] args )
{
ServerApp application = new ServerApp();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
application.execute();
}
private static class ServerApp extends JFrame {
private JTextArea displayArea;
private ServerSocket server;
private ExecutorService runChat;
private List<chatClient> clients;
public ServerApp() {
super("Aurora Server");
runChat = Executors.newCachedThreadPool();
clients = new ArrayList<>();
public class ServerTest
{
public static void main( String[] args )
{
ServerApp application = new ServerApp();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
application.execute();
}
private static class ServerApp extends JFrame {
private JTextArea displayArea;
private ServerSocket server;
private ExecutorService runChat;
private List<chatClient> clients;
public ServerApp() {
super("Aurora Server");
runChat = Executors.newCachedThreadPool();
clients = new ArrayList<>();
Java Assignment Codes 46
try {
server = new ServerSocket(12345, 100);
} catch (IOException ioException) {
ioException.printStackTrace();
}
displayArea = new JTextArea();
displayArea.setEditable(false);
displayArea.setBackground(Color.BLACK);
displayArea.setForeground(Color.GREEN);
add(new JScrollPane(displayArea), BorderLayout.CENTER);
setSize(600, 300);
setVisible(true);
displayMessage("Morse Code server started");
}
public void execute() {
try {
server = new ServerSocket(12345, 100);
} catch (IOException ioException) {
ioException.printStackTrace();
}
displayArea = new JTextArea();
displayArea.setEditable(false);
displayArea.setBackground(Color.BLACK);
displayArea.setForeground(Color.GREEN);
add(new JScrollPane(displayArea), BorderLayout.CENTER);
setSize(600, 300);
setVisible(true);
displayMessage("Morse Code server started");
}
public void execute() {
Secure Best Marks with AI Grader
Need help grading? Try our AI Grader for instant feedback on your assignments.
Java Assignment Codes 47
while (clients.size() < 100) {
try {
clients.add(new chatClient(server.accept(), clients.size()));
displayMessage("Connection " + clients.size() + " received from: "
+ clients.get(clients.size() - 1).connection.getInetAddress().getHostName());
runChat.execute(clients.get(clients.size() - 1));
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}
private void displayMessage(final String messageToDisplay) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
displayArea.append(messageToDisplay + "\n");
}
while (clients.size() < 100) {
try {
clients.add(new chatClient(server.accept(), clients.size()));
displayMessage("Connection " + clients.size() + " received from: "
+ clients.get(clients.size() - 1).connection.getInetAddress().getHostName());
runChat.execute(clients.get(clients.size() - 1));
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}
private void displayMessage(final String messageToDisplay) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
displayArea.append(messageToDisplay + "\n");
}
Java Assignment Codes 48
}
);
}
private void sendData(String message) {
try {
for (chatClient client : clients) {
client.output.writeObject(message);
client.output.flush();
}
} catch (IOException ioException) {
displayMessage("Error writing object");
}
}
private void removeClient(int removeClientNum) {
displayMessage("Removing client " + removeClientNum);
clients.remove(removeClientNum);
if ((clients.size() > 0) && (removeClientNum < clients.size())) {
for (chatClient client : clients) {
if (client.clientNumber != 0) {
}
);
}
private void sendData(String message) {
try {
for (chatClient client : clients) {
client.output.writeObject(message);
client.output.flush();
}
} catch (IOException ioException) {
displayMessage("Error writing object");
}
}
private void removeClient(int removeClientNum) {
displayMessage("Removing client " + removeClientNum);
clients.remove(removeClientNum);
if ((clients.size() > 0) && (removeClientNum < clients.size())) {
for (chatClient client : clients) {
if (client.clientNumber != 0) {
Java Assignment Codes 49
client.clientNumber -= 1;
}
}
}
displayMessage("Clients renumbered");
}
private class chatClient implements Runnable {
private ObjectOutputStream output;
private ObjectInputStream input;
private Socket connection;
private int clientNumber;
private String clientName;
private Boolean openConnection;
public chatClient(Socket socket, int number) {
connection = socket;
clientNumber = number;
try {
getStreams();
client.clientNumber -= 1;
}
}
}
displayMessage("Clients renumbered");
}
private class chatClient implements Runnable {
private ObjectOutputStream output;
private ObjectInputStream input;
private Socket connection;
private int clientNumber;
private String clientName;
private Boolean openConnection;
public chatClient(Socket socket, int number) {
connection = socket;
clientNumber = number;
try {
getStreams();
Paraphrase This Document
Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Java Assignment Codes 50
} catch (IOException ioException) {
ioException.printStackTrace();
}
openConnection = true;
}
private void getStreams() throws IOException {
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
try {
clientName = (String) input.readObject();
} catch (ClassNotFoundException classNotFoundException) {
}
displayMessage("Got I/O streams for client " + clientName + "(" + clientNumber + ")");
}
private void processConnection() throws IOException {
String message = "Client connection " + clientNumber + " successful";
while (openConnection) {
try {
} catch (IOException ioException) {
ioException.printStackTrace();
}
openConnection = true;
}
private void getStreams() throws IOException {
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
try {
clientName = (String) input.readObject();
} catch (ClassNotFoundException classNotFoundException) {
}
displayMessage("Got I/O streams for client " + clientName + "(" + clientNumber + ")");
}
private void processConnection() throws IOException {
String message = "Client connection " + clientNumber + " successful";
while (openConnection) {
try {
Java Assignment Codes 51
message = (String) input.readObject();
if (message.equalsIgnoreCase("\\quit")) {
openConnection = false;
} else {
sendData(clientName + "\n" + message);
}
} catch (ClassNotFoundException classNotFoundException) {
sendData("Unknown object type received");
}
}
}
private void closeConnection() {
displayMessage("\nTerminating connection for client " + clientNumber + "\n");
try {
output.close();
input.close();
connection.close();
} catch (IOException ioException) {
ioException.printStackTrace();
message = (String) input.readObject();
if (message.equalsIgnoreCase("\\quit")) {
openConnection = false;
} else {
sendData(clientName + "\n" + message);
}
} catch (ClassNotFoundException classNotFoundException) {
sendData("Unknown object type received");
}
}
}
private void closeConnection() {
displayMessage("\nTerminating connection for client " + clientNumber + "\n");
try {
output.close();
input.close();
connection.close();
} catch (IOException ioException) {
ioException.printStackTrace();
Java Assignment Codes 52
}
}
public void run() {
try {
processConnection();
} catch (EOFException eofException) {
sendData("\nServer terminated connection for client " + clientNumber + "\n");
} catch (IOException ioException) {
ioException.printStackTrace();
} finally {
closeConnection();
removeClient(clientNumber);
Thread.currentThread().interrupt();
}
}
}
}
}
}
}
public void run() {
try {
processConnection();
} catch (EOFException eofException) {
sendData("\nServer terminated connection for client " + clientNumber + "\n");
} catch (IOException ioException) {
ioException.printStackTrace();
} finally {
closeConnection();
removeClient(clientNumber);
Thread.currentThread().interrupt();
}
}
}
}
}
1 out of 52
Related Documents
Your All-in-One AI-Powered Toolkit for Academic Success.
 +13062052269
info@desklib.com
Available 24*7 on WhatsApp / Email
Unlock your academic potential
© 2024  |  Zucol Services PVT LTD  |  All rights reserved.