Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package quadraticcalculation;
- import java.io.*;
- import java.net.*;
- import java.text.DateFormat;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- import java.util.Scanner;
- public class QuadraticServer {
- static final int PORTNUMBER = 5010;
- static void pStr(String p) {
- System.out.println(p);
- }
- void runServer() {
- ServerSocket server;
- Socket connection;
- try {
- pStr("Creating Server Socket " + PORTNUMBER + " . . . ");
- server = new ServerSocket(PORTNUMBER);
- pStr("SUCCESS!!!");
- while (true) {
- pStr("Waiting for connection.");
- connection = server.accept();
- pStr("Done");
- QuadraticCalculationThread t = new QuadraticCalculationThread(connection);
- t.start();
- pStr("");
- pStr("Communicating with " + connection.getInetAddress() + " " + connection.getPort());
- DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
- Date date = new Date();
- pStr("Time: " + dateFormat.format(date));
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- public class QuadraticCalculationThread extends Thread {
- private Socket connection;
- QuadraticCalculationThread(Socket x) {
- connection = x;
- }
- public void run() {
- try (Scanner input = new Scanner(connection.getInputStream());
- PrintWriter output = new PrintWriter(connection.getOutputStream());
- ) {
- double a = 0, b = 0, c = 0, r1 = 0, r2 = 0;
- int status = 0;
- String statmsg = null;
- try {
- a = Double.parseDouble(input.nextLine());
- b = Double.parseDouble(input.nextLine());
- c = Double.parseDouble(input.nextLine());
- if (a == 0) {
- status = -1;
- statmsg = "Not a quadratic equation.";
- } else {
- double discrim = b * b - 4 * a * c;
- if (discrim < 0) {
- statmsg = "No real roots.";
- } else if (discrim == 0) {
- status = 1;
- statmsg = "One real root.";
- r1 = (-b + Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a);
- } else if (discrim > 0) {
- status = 2;
- statmsg = "Two real roots.";
- r1 = (-b + Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a);
- r2 = (-b - Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a);
- }
- }
- } catch (Exception e){
- status = -1;
- statmsg = "ERROR: Please enter an actual number.";
- }
- output.println(status);
- output.flush();
- output.println(statmsg);
- output.flush();
- if (status == 1) { //If only one root.
- output.println(r1);
- output.flush();
- } else if (status == 2) { //If two roots.
- output.println(r1);
- output.flush();
- output.println(r2);
- output.flush();
- }
- } catch (Exception e) {
- pStr("ERROR!");
- } finally {
- try {
- connection.close();
- } catch (Exception e) {
- }
- }
- }
- }
- public static void main(String args[]) {
- QuadraticServer s = new QuadraticServer();
- s.runServer();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement