Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit f95e549

Browse files
Merge pull request #71 from HarryDulaney/new-solutions
bug fix ex 31 023
2 parents dc8c0c9 + 0c07efd commit f95e549

File tree

3 files changed

+114
-128
lines changed

3 files changed

+114
-128
lines changed

‎ch_31/exercise31_02/Exercise31_02.java

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,10 @@ public class Exercise31_02 extends Application {
1515
@Override
1616
public void start(Stage primaryStage) throws Exception {
1717
System.out.println("##-_-_--_--_--__-_-- Starting: Exercise31_02 --_-__--__--__--_--_--##");
18-
Platform.runLater(() -> new Exercise31_02Server().start(new Stage()));
19-
Platform.runLater(() -> new Exercise31_02Client().start(new Stage()));
18+
new Thread(() -> {
19+
Platform.runLater(() -> new Exercise31_02Server().start(new Stage()));
20+
Platform.runLater(() -> new Exercise31_02Client().start(new Stage()));
21+
}).start();
22+
2023
}
2124
}
Lines changed: 69 additions & 83 deletions
Original file line numberDiff line numberDiff line change
@@ -1,106 +1,92 @@
11
package ch_31.exercise31_02;
22

33
import javafx.application.Application;
4-
import javafx.event.ActionEvent;
5-
import javafx.event.EventHandler;
6-
import javafx.geometry.HPos;
74
import javafx.geometry.Pos;
8-
import javafx.geometry.VPos;
95
import javafx.scene.Scene;
10-
import javafx.scene.control.Button;
11-
import javafx.scene.control.Label;
12-
import javafx.scene.control.TextArea;
13-
import javafx.scene.control.TextField;
6+
import javafx.scene.control.*;
7+
import javafx.scene.layout.BorderPane;
148
import javafx.scene.layout.GridPane;
159
import javafx.stage.Stage;
1610

17-
import java.io.*;
11+
import java.io.DataInputStream;
12+
import java.io.DataOutputStream;
13+
import java.io.IOException;
1814
import java.net.Socket;
19-
2015
public class Exercise31_02Client extends Application {
21-
private TextField weightTextInput = new TextField();
22-
private TextField heightTextInput = new TextField();
23-
private TextArea displayResultTextArea = new TextArea();
16+
DataOutputStream toServer = null;
17+
DataInputStream fromServer = null;
2418

25-
private Button submitButton = new Button("Submit");
19+
// Text fields for BMI information
20+
private TextField tfWeight = new TextField();
21+
private TextField tfHeight = new TextField();
2622

27-
// Host name or ip
28-
String host = "localhost";
23+
@Override // Override the start method in the Application class
24+
public void start(Stage primaryStage) {
25+
// Main pane
26+
BorderPane pane = new BorderPane();
2927

30-
private ObjectOutputStream toServer;
31-
private DataInputStream fromServer;
28+
// Set text field alignment right
29+
tfWeight.setAlignment(Pos.BASELINE_RIGHT);
30+
tfHeight.setAlignment(Pos.BASELINE_RIGHT);
3231

33-
public Exercise31_02Client() {
34-
System.out.println("##-_-_--_--_--__-_-- Starting: Exercise31_02Client --_-__--__--__--_--_--##");
35-
}
32+
// Create button to send BMI info to server
33+
Button btSubmit = new Button("Submit");
3634

37-
@Override
38-
public void start(Stage primaryStage) {
39-
Stage stage = new Stage();
40-
GridPane pane = new GridPane();
41-
pane.add(new Label("Weight in pounds"), 0, 0);
42-
pane.add(weightTextInput, 1, 0);
43-
pane.add(new Label("Height in inches"), 0, 1);
44-
pane.add(heightTextInput, 1, 1);
45-
pane.add(submitButton, 1, 3);
46-
pane.add(displayResultTextArea, 1, 4);
47-
GridPane.setHalignment(submitButton, HPos.RIGHT);
48-
GridPane.setValignment(displayResultTextArea, VPos.BOTTOM);
49-
pane.setAlignment(Pos.CENTER);
50-
weightTextInput.setPrefColumnCount(15);
51-
heightTextInput.setPrefColumnCount(15);
52-
submitButton.setOnAction(new ButtonListener());
53-
54-
Scene scene = new Scene(pane, 450, 200);
55-
stage.setTitle("BMI Client");
56-
stage.setScene(scene);
57-
stage.show();
58-
59-
try (Socket socket = new Socket(host, 8000)) {
60-
// Create an output stream to the server
61-
toServer = new ObjectOutputStream(socket.getOutputStream());
62-
// Create an input stream from the server
63-
fromServer = new DataInputStream(socket.getInputStream());
64-
} catch (IOException ex) {
65-
System.out.println("##----------- Client Error: IOException: " + ex.getMessage() + " -----------##");
66-
}
67-
}
35+
// Pane to hold BMI information and submit button
36+
GridPane paneForBmiInfo = new GridPane();
37+
paneForBmiInfo.add(new Label("Weight in pounds"), 0, 0);
38+
paneForBmiInfo.add(tfWeight, 1, 0);
39+
paneForBmiInfo.add(new Label("Height in inches"), 0, 1);
40+
paneForBmiInfo.add(tfHeight, 1, 1);
41+
paneForBmiInfo.add(btSubmit, 2, 1);
42+
43+
// Text Area to display contents
44+
TextArea ta = new TextArea();
45+
pane.setTop(paneForBmiInfo);
46+
pane.setCenter(new ScrollPane(ta));
6847

69-
/**
70-
* Custom event handler for the submit button
71-
*/
72-
private class ButtonListener implements EventHandler<ActionEvent> {
73-
@Override
74-
public void handle(ActionEvent e) {
48+
// Create a scene and place it in the stage
49+
Scene scene = new Scene(pane, 400, 200);
50+
primaryStage.setTitle("Exercise31_01Client"); // Set the stage title
51+
primaryStage.setScene(scene); // Place the scene in the stage
52+
primaryStage.show(); // Display the stage
53+
54+
btSubmit.setOnAction(e -> {
7555
try {
76-
// Get weight and height from the text fields
77-
double weight = Double.parseDouble(weightTextInput.getText().trim());
78-
double height = Double.parseDouble(heightTextInput.getText().trim());
79-
// Create a BmiDto and send to the server
80-
BmiDto s = new BmiDto(weight, height);
81-
toServer.writeObject(s);
56+
// Get the weight and height from the text fields
57+
double weight = Double.parseDouble(tfWeight.getText().trim());
58+
double height = Double.parseDouble(tfHeight.getText().trim());
59+
60+
// Send the BMI information to the server
61+
toServer.writeDouble(weight);
62+
toServer.writeDouble(height);
8263
toServer.flush();
83-
// Get resulting BMI from the server
84-
double bmi = fromServer.readDouble();
85-
// Display to the text area
86-
displayResultTextArea.setText("Weight: " + weight + "\nHeight: " + height + "\nBMI is: " + bmi
87-
+ "\n" + getCategory(bmi));
88-
} catch (IOException ex) {
89-
System.out.println("##----------- Client Error: IOException: " + ex.getMessage() + " -----------##");
64+
65+
// Get string from the server
66+
String bmi = fromServer.readUTF();
67+
68+
// Display to text area
69+
ta.appendText("Weight: " + weight + '\n');
70+
ta.appendText("Height: " + height + '\n');
71+
ta.appendText(bmi + '\n');
9072
}
91-
}
92-
}
73+
catch (IOException ex) {
74+
System.err.println(ex);
75+
}
76+
});
9377

94-
private String getCategory(double bmi) {
95-
if (bmi < 18.5) {
96-
return "Underweight";
97-
} else if (bmi < 25) {
98-
return "Normal";
99-
} else if (bmi < 30) {
100-
return "Overweight";
101-
} else {
102-
return "Obese";
78+
try {
79+
// Create a socket to connect to the server
80+
Socket socket = new Socket("localhost", 8000);
81+
82+
// Create an input stream to receive data from the server
83+
fromServer = new DataInputStream(socket.getInputStream());
84+
85+
// Create an output stream to send data to the server
86+
toServer = new DataOutputStream(socket.getOutputStream());
87+
}
88+
catch (IOException ex) {
89+
ta.appendText(ex.toString() + '\n');
10390
}
10491
}
105-
10692
}

‎ch_31/exercise31_02/Exercise31_02Server.java

Lines changed: 40 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -11,67 +11,64 @@
1111
import java.net.ServerSocket;
1212
import java.net.Socket;
1313
import java.util.Date;
14-
import java.util.Objects;
15-
import java.util.concurrent.atomic.AtomicBoolean;
14+
1615

1716
public class Exercise31_02Server extends Application {
1817
private static final double KILOGRAMS_PER_POUND = 0.45359237;
1918
private static final double METERS_PER_INCH = 0.0254;
2019

21-
private AtomicBoolean isRunning = new AtomicBoolean(true);
22-
23-
public Exercise31_02Server() {
24-
System.out.println("##-_-_--_--_--__-_-- Starting: Exercise31_02Server --_-__--__--__--_--_--##");
25-
}
26-
27-
2820
@Override
2921
public void start(Stage primaryStage) {
3022
TextArea displayLogTextArea = new TextArea();
3123
Scene scene = new Scene(new ScrollPane(displayLogTextArea), 450, 200);
3224
primaryStage.setTitle("TicTacToeServer");
3325
primaryStage.setScene(scene);
3426
primaryStage.show();
35-
new Thread(() -> runServer(displayLogTextArea)).start();
36-
}
27+
new Thread(() -> {
28+
try {
29+
ServerSocket serverSocket = new ServerSocket(8000);
30+
Platform.runLater(() ->
31+
displayLogTextArea.appendText("Exercise31_02Server started at "
32+
+ new Date() + '\n'));
3733

38-
private void runServer(TextArea displayLogTextArea) {
39-
/* Create a server socket. Use try with resources to close the socket automatically */
40-
try (ServerSocket serverSocket = new ServerSocket(8000)) {
41-
// Listen for a connection request
42-
Socket socket = socket = serverSocket.accept();
43-
// Create data input and output streams
44-
try (ObjectInputStream inputFromClient = new ObjectInputStream(
45-
socket.getInputStream())) {
46-
try (DataOutputStream outputToClient = new DataOutputStream(
47-
socket.getOutputStream())) {
34+
Socket socket = serverSocket.accept();
35+
DataInputStream inputFromClient = new DataInputStream(
36+
socket.getInputStream());
37+
DataOutputStream outputToClient = new DataOutputStream(
38+
socket.getOutputStream());
4839

49-
Platform.runLater(() -> displayLogTextArea.appendText(new Date() +
50-
": Server started at socket 8000\n"));
51-
while (true) {
52-
if (!isRunning.get()) {
53-
break;
54-
}
55-
if (inputFromClient.available() > 0) {
56-
// Receive Object from the client
57-
Object object = inputFromClient.readObject();
58-
if (Objects.nonNull(object) && object instanceof BmiDto) {
59-
BmiDto bmiDto = (BmiDto) object;
60-
double weight = bmiDto.getWeight();
61-
double height = bmiDto.getHeight();
62-
double bmi = calculateBmi(weight, height);
63-
// Send area back to the client
64-
outputToClient.writeDouble(bmi);
65-
}
66-
}
40+
while (true) {
41+
Date date = new Date();
42+
double weight = inputFromClient.readDouble();
43+
double height = inputFromClient.readDouble();
44+
double weightInKilograms = weight * KILOGRAMS_PER_POUND;
45+
double heightInMeters = height * METERS_PER_INCH;
46+
double bmi = calculateBmi(weightInKilograms, heightInMeters);
47+
StringBuilder bmiString = new StringBuilder("BMI is " +
48+
String.format("%.2f", bmi) + ". ");
6749

50+
if (bmi < 18.5) {
51+
bmiString.append("Underweight");
52+
} else if (bmi < 25) {
53+
bmiString.append("Normal");
54+
} else if (bmi < 30) {
55+
bmiString.append("Overweight");
56+
} else {
57+
bmiString.append("Obese");
6858
}
59+
outputToClient.writeUTF(bmiString.toString());
60+
61+
Platform.runLater(() -> {
62+
displayLogTextArea.appendText("Connected to a client at " + date + '\n');
63+
displayLogTextArea.appendText("Weight: " + weight + '\n');
64+
displayLogTextArea.appendText("Height: " + height + '\n');
65+
displayLogTextArea.appendText(bmiString.toString() + '\n');
66+
});
6967
}
68+
} catch (IOException ex) {
69+
ex.printStackTrace();
7070
}
71-
72-
} catch (ClassNotFoundException | IOException ex) {
73-
System.out.println("##----------- Server Error: Exception: " + ex.getMessage() + " -----------##");
74-
}
71+
}).start();
7572
}
7673

7774
private double calculateBmi(double weight, double height) {

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /