Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Name: Phat Tu
- * Date: 04/28/17
- * Course Number: CSC-112-D01
- * Course Name: Intermediate Java
- * Problem Number: HW #10
- * Email: pgtu0001@student.stcc.edu
- * Create a server-client that calculates the quadratic formula.
- */
- import java.net.*;
- import java.text.DateFormat;
- import java.text.SimpleDateFormat;
- import java.io.*;
- import java.util.Date;
- import java.util.Scanner;
- public class QuadraticServer implements Runnable {
- private int portNum;
- public QuadraticServer(int port) {
- this.portNum = port;
- }
- public class ThreadConnect extends Thread {
- private Socket connection;
- ThreadConnect(Socket x) {
- connection = x;
- }
- public void run() {
- PrintWriter pw = null;
- Scanner sc = null;
- try {
- pw = new PrintWriter(connection.getOutputStream());
- sc = new Scanner(connection.getInputStream());
- double a, b, c, discriminant, root1, root2;
- try {
- a = Double.parseDouble(sc.nextLine());
- b = Double.parseDouble(sc.nextLine());
- c = Double.parseDouble(sc.nextLine());
- discriminant = b * b - 4 * a * c;
- root1 = ((-1 * b) + Math.sqrt(discriminant)) / (2 * a);
- root2 = ((-1 * b) - Math.sqrt(discriminant)) / (2 * a);
- pw.println(status(discriminant));
- switch (status(discriminant)) {
- case 0:
- break;
- case 1:
- pw.println(root1);
- break;
- case 2: {
- pw.println(root1);
- pw.println(root2);
- }
- break;
- default:
- throw new RuntimeException("Operation has failed.");
- }
- pw.flush();
- } catch (Exception e) {
- }
- } catch (Exception e) {
- } finally {
- try {
- sc.close();
- } catch (Exception e) {
- }
- try {
- pw.close();
- } catch (Exception e) {
- }
- try {
- connection.close();
- } catch (Exception e) {
- }
- }
- }
- private int status(double discriminant) {
- if (discriminant < 0)
- return 0;
- else if (discriminant == 0)
- return 1;
- else if (discriminant > 0)
- return 2;
- return -1;
- }
- }
- @Override
- public void run() {
- ServerSocket server;
- try {
- server = new ServerSocket(this.portNum);
- while (true) {
- message("Waiting for connection.");
- Socket connection = server.accept();
- logging(connection);
- new Thread(new ThreadConnect(connection)).start();
- message("Done.\n");
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- private void logging(Socket connection) {
- message("");
- message("Communicating with " + connection.getInetAddress() + " " + connection.getPort());
- DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
- Date date = new Date();
- message("Time: " + dateFormat.format(date));
- }
- private static void message(String string) {
- System.out.println(string);
- }
- public static void main(String[] args) {
- QuadraticServer q = new QuadraticServer(5012);
- new Thread(q).start();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement