Question

Java: In this assignment, you will create an accumulator accumulator-calculator that displays a sad face “...

Java:


In this assignment, you will create an accumulator accumulator-calculator that displays a sad face “ :-( “ whenever the number displayed by the calculator is negative and a happy face “ :-) ” whenever the number displayed is positive.
The calculator responds to the following commands: num + , num - , num * , num / and C ( Clear ).

After initial run, if the user clicks 8 and then presses the “+” button for example, the accumulator value displays 8 in one field and a happy face in the other. If the second number entered by the user is 9 followed by “-“ button, the accumulator displays -1 and the face changes to the sad mode. If the next command is C, the accumulator will be initialized back to zero and the two Text Fields will be cleared

Notice also that, this kind of calculator accepts only single digit numbers as input at any given time. (i.e. Single digit number followed by an operation).

import javax.swing.JOptionPane;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;


public class StartupAccumulatorCalculator_JavaFX extends Application {

private TextField txtOutput = new TextField();
TextField txtFace = new TextField();

private float inputValue;

private Calculator calculator = new Calculator();
private Face face = new Face();

public static void main(String[] args) {
launch(args);
}
@Override // Override the start method in the Application class
public void start(Stage primaryStage) {
// Create a scene by calling the getPane() method and place it in the stage
Scene scene = new Scene(getPane(), 200, 250);
primaryStage.setTitle("Fun Calculator"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
}


/**
* getPane() returns a pane to be used with the scene of this calculator.
* In this method, you will need to generate the GUI of this calculator. Use different kinds of panes for alignment
* This method will also implement the event handlers for each button press. You may elect to divide the load among multiple methods if you prefer.
*/
protected BorderPane getPane() {

   BorderPane mainPane = new BorderPane();
   //Your code goes here .....
  
  
  
  
  
  
  
  
  
  
  
  
return mainPane;
}
//----------------------------------------------------------
/**
* This method checks the accumulator value and by calling getAccumValue(). based on this value it either calls the
* face.makeHappy() or face.makeSad() and sets the face to happy/sad in txtFace
* Will be called whenever one of the operation buttons is pressed
*/
public void display(){

   //Your code goes here .....
     
     
     
     
     
     
   }
}
//*********************************************************
class Calculator
{
private float currentAccumValue;
public Calculator (){
       currentAccumValue = 0.0f;
}

public void add(float inputValue){
currentAccumValue+= inputValue;
}

public void subtract(float inputValue){
currentAccumValue-= inputValue;
}

public void multiply(float inputValue){
currentAccumValue*= inputValue;
}

public void divide(float inputValue){
   if(inputValue == 0) {
JOptionPane.showMessageDialog(null, "Error: You cannot divide by 0!", "Error",
JOptionPane.INFORMATION_MESSAGE);
   } else {
   currentAccumValue /= inputValue;
   }
}

public void clearAccum(){
currentAccumValue = 0;
}
public float getAccumValue(){
return currentAccumValue;
}
}
//*********************************************************

class Face
{
private boolean faceState;

public Face(){
   makeHappy();
}

public void makeHappy(){
faceState = true;
}

public void makeSad(){
faceState = false;
}

public boolean getFaceState(){
return faceState;

}
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks

// StartupAccumulatorCalculator_JavaFX.java

import javax.swing.JOptionPane;

import javafx.application.Application;

import javafx.geometry.Insets;

import javafx.stage.Stage;

import javafx.scene.Scene;

import javafx.scene.control.Button;

import javafx.scene.control.TextField;

import javafx.geometry.Pos;

import javafx.scene.control.Label;

import javafx.scene.layout.BorderPane;

import javafx.scene.layout.GridPane;

import javafx.scene.layout.HBox;

public class StartupAccumulatorCalculator_JavaFX extends Application {

    private TextField txtOutput = new TextField();

    TextField txtFace = new TextField();

    private float inputValue;

    private Calculator calculator = new Calculator();

    private Face face = new Face();

    public static void main(String[] args) {

       launch(args);

    }

    @Override // Override the start method in the Application class

    public void start(Stage primaryStage) {

        // Create a scene by calling the getPane() method and place it in the stage

        Scene scene = new Scene(getPane(),300,300);

        primaryStage.setTitle("Fun Calculator"); // Set the stage title

        primaryStage.setScene(scene); // Place the scene in the stage

        primaryStage.show(); // Display the stage

    }

    /**

     * getPane() returns a pane to be used with the scene of this calculator. In

     * this method, you will need to generate the GUI of this calculator. Use

     * different kinds of panes for alignment This method will also implement

     * the event handlers for each button press. You may elect to divide the

     * load among multiple methods if you prefer.

     */

    protected BorderPane getPane() {

        BorderPane mainPane = new BorderPane();

        //setting some padding

        mainPane.setPadding(new Insets(20));

        //creating an HBox to include output text and face text

        HBox hbox = new HBox(txtOutput, txtFace);

        hbox.setSpacing(10);

        //aligning center

        hbox.setAlignment(Pos.CENTER);

        //creating a 2D array containing the value needs to be displayed on buttons

        //in that order

        Object buttons[][] = new Object[][]{{7, 8, 9, "/"}, {4, 5, 6, "*"}, {1, 2, 3, "-"}, {null, 0, "C", "+"}};

        //creating a grid for the buttons, adjusting attributes

        GridPane buttonsPane = new GridPane();

        buttonsPane.setHgap(10);

        buttonsPane.setVgap(10);

        buttonsPane.setAlignment(Pos.CENTER);

        buttonsPane.setPadding(new Insets(20));

        //looping for each row and column

        for (int i = 0; i < 4; i++) {

            for (int j = 0; j < 4; j++) {

                //adding a Button to grid pane if element at i, j in buttons array

                //is not null, else a dummy label node

                if (buttons[i][j] != null) {

                    Button b = new Button(buttons[i][j].toString());

                    //adding action listener to call handleClick method,

                    //passing the text of button as argument

                    b.setOnAction(e -> handleClick(b.getText()));

                    //adding to grid at column j and row i

                    buttonsPane.add(b, j, i);

                } else {

                    //dummy node, just to fill vacant space

                    buttonsPane.add(new Label(""), j, i);

                }

            }

        }

       

        //adding hbox to top and buttons to center

        mainPane.setTop(hbox);

        mainPane.setCenter(buttonsPane);

        //Your code goes here .....

        return mainPane;

    }

//----------------------------------------------------------

    /**

     * This method checks the accumulator value and by calling getAccumValue().

     * based on this value it either calls the face.makeHappy() or

     * face.makeSad() and sets the face to happy/sad in txtFace Will be called

     * whenever one of the operation buttons is pressed

     */

    public void display() {

        if (calculator.getAccumValue() >= 0) {

            //happy

            face.makeHappy();

        } else {

            //sad

            face.makeSad();

        }

        if (face.getFaceState()) {

            //setting happy face

            txtFace.setText(":-)");

        } else {

            //setting sad face

            txtFace.setText(":-(");

        }

    }

   

    //event handler for button clicks

    private void handleClick(String str) {

        //getting the character on the label of clicked button

        char c = str.toUpperCase().charAt(0);

        //if it is a digit, parsing digit and assigning to inputValue

        if (Character.isDigit(c)) {

            inputValue = Character.digit(c, 10);

        } else {

            //if it is an operator, finding and performing the selected operation

          switch (c) {

                case '/':

                    //division

                    calculator.divide(inputValue);

                    txtOutput.setText("" + calculator.getAccumValue());

                    display();

                    break;

                case '+':

                    //addition

                    calculator.add(inputValue);

                    txtOutput.setText("" + calculator.getAccumValue());

                    display();

                    break;

                case '-':

                    //subtraction

                    calculator.subtract(inputValue);

                    txtOutput.setText("" + calculator.getAccumValue());

                    display();

                    break;

                case '*':

                    //multiplication

                    calculator.multiply(inputValue);

                    txtOutput.setText("" + calculator.getAccumValue());

                    display();

                    break;

                case 'C':

                    //reset/clear

                    calculator.clearAccum();

                    txtFace.setText("");

                    txtOutput.setText("");

                    break;

            }

        }

    }

}

//*********************************************************

class Calculator {

    private float currentAccumValue;

    public Calculator() {

        currentAccumValue = 0.0f;

    }

    public void add(float inputValue) {

        currentAccumValue += inputValue;

    }

    public void subtract(float inputValue) {

        currentAccumValue -= inputValue;

    }

    public void multiply(float inputValue) {

        currentAccumValue *= inputValue;

    }

    public void divide(float inputValue) {

        if (inputValue == 0) {

            JOptionPane.showMessageDialog(null, "Error: You cannot divide by 0!", "Error",

                    JOptionPane.INFORMATION_MESSAGE);

        } else {

            currentAccumValue /= inputValue;

        }

    }

    public void clearAccum() {

        currentAccumValue = 0;

    }

    public float getAccumValue() {

        return currentAccumValue;

    }

}

//*********************************************************

class Face {

    private boolean faceState;

    public Face() {

        makeHappy();

    }

    public void makeHappy() {

        faceState = true;

    }

    public void makeSad() {

        faceState = false;

    }

    public boolean getFaceState() {

        return faceState;

    }

}

/*OUTPUT*/


Add a comment
Know the answer?
Add Answer to:
Java: In this assignment, you will create an accumulator accumulator-calculator that displays a sad face “...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • use this code of converting Km to miles , to create Temperature converter by using java...

    use this code of converting Km to miles , to create Temperature converter by using java FX import javafx.application.Application; import javafx.stage.Stage; import javafx.scene.Scene; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.geometry.Pos; import javafx.geometry.Insets; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.control.Button; import javafx.event.EventHandler; import javafx.event.ActionEvent; /** * Kilometer Converter application */ public class KiloConverter extends Application { // Fields private TextField kiloTextField; private Label resultLabel; public static void main(String[] args) { // Launch the application. launch(args); } @Override public void start(Stage primaryStage) { //...

  • please help me debug this Create a Future Value Calculator that displays error messages in labels.GUISpecificationsStart...

    please help me debug this Create a Future Value Calculator that displays error messages in labels.GUISpecificationsStart with the JavaFX version of the Future Value application presented in chapter 17. Create error message labels for each text field that accepts user input. Use the Validation class from chapter 17 to validate user input.Format the application so that the controls don’t change position when error messages are displayed. package murach.business; public class Calculation {        public static final int MONTHS_IN_YEAR =...

  • # Java import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.stage.Stage; public class Test extends Application {...

    # Java import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.stage.Stage; public class Test extends Application {   @Override // Override the start method in the Application class   public void start(Stage primaryStage) {     // Create a button and place it in the scene     Button btOK = new Button("OK");     btOK.setOnAction(e -> System.out.println("OK 1"));     btOK.setOnAction(e -> System.out.println("OK 2"));     Scene scene = new Scene(btOK, 200, 250);     primaryStage.setTitle("MyJavaFX"); // Set the stage title     primaryStage.setScene(scene); // Place the scene in the stage     primaryStage.show(); // Display the stage...

  • You may adjust the code as you want. Thank you! CODING HERE: import javafx.application.Application; import javafx.event.*;...

    You may adjust the code as you want. Thank you! CODING HERE: import javafx.application.Application; import javafx.event.*; import javafx.scene.*; import javafx.scene.control.*; import javafx.scene.layout.*; import javafx.stage.*; import javafx.geometry.*; public class OrderSystem extends Application implements EventHandler<ActionEvent> { // Attributes for GUI private Stage stage; // The entire window, including title bar and borders private Scene scene; // Interior of window private BorderPane layout; // Add four labels private Label itemLabel = new Label("Item Name:"); private Label numberLabel = new Label("Number:"); private Label costLabel...

  • Examine the following code and complete missing parts: import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets;...

    Examine the following code and complete missing parts: import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.stage.Stage; public class NtoThePowerOfN extends Application{ @Override public void start(Stage primaryStage) throws Exception { TextField inputField; TextField outputField; VBox base = new VBox(10); base.setPadding(new Insets(10)); base.setAlignment(Pos.CENTER); // // A: input components - label and text field // // // B: button - to compute the value // // //...

  • (5 points) Analyze the following codes. b) import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import...

    (5 points) Analyze the following codes. b) import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.layout.HBox; import javafx.stage.Stage; public class Test extends Application { @Override // Override the start method in the Application class public void start(Stage primaryStage) { Button btOK = new Button("OK"); Button btCancel = new Button("Cancel"); EventHandler<ActionEvent> handler = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { System.out.println("The OK button is clicked"); } }; btOK.setOnAction(handler); btCancel.setOnAction(handler); HBox pane = new HBox(5); pane.getChildren().addAll(btOK, btCancel); Scene...

  • I have been messing around with java lately and I have made this calculator. Is there...

    I have been messing around with java lately and I have made this calculator. Is there any way that I would be able to get a different sound to play on each different button 1 - 9 like a nokia phone? Thank you. *SOURCE CODE* import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; class Calculator extends JFrame { private final Font BIGGER_FONT = new Font("monspaced",Font.PLAIN, 20); private JTextField textfield; private boolean number = true; private String equalOp = "="; private...

  • Create a simple calculator. Your interface should contain two input boxes in which the user can...

    Create a simple calculator. Your interface should contain two input boxes in which the user can put two numbers. There should be four buttons: add, subtract, multiply, and divide. When the user inputs two number and clicks on an operation button, the result should be displayed in the label. Can some please help my code that i came up with just displays a pop box with no words or nothing! I'm not the best at coding. Any tips or advice...

  • Use Kilometer Converter application code to write Temperature Converter application to convert degrees Fahrenheit into degrees...

    Use Kilometer Converter application code to write Temperature Converter application to convert degrees Fahrenheit into degrees Celsius ((F - 32)*5/9). It needs to be JavaFX 1 import javafx.application. Application; 2 import javafx.stage. Stage; 3 import javafx.scene. Scene; 4 import javafx.scene.layout.HBox; 5 import javafx.scene.layout. VBox; 6 import javafx.geometry.Pos; 7 import javafx.geometry.Insets; 8 import javafx.scene.control.Label; 9 import javafx.scene.control. TextField; 10 import javafx.scene.control.Button; 11 import javafx.event. EventHandler; 12 import javafx.event. ActionEvent; 13 14 ** 15 * Kilometer Converter application 16 17 18 public...

  • Modify the JavaFX TipCalculator application program to allow the user to enter the number of persons...

    Modify the JavaFX TipCalculator application program to allow the user to enter the number of persons in the party through a text field. Calculate and display the amount owed by each person in the party if the bill is to be split evenly among the party members. /////////// TipCalculatorController.java: import java.math.BigDecimal; import java.math.RoundingMode; import java.text.NumberFormat; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.control.Slider; import javafx.scene.control.TextField; public class TipCalculatorController { // formatters for currency and percentages private...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT