Сохраните значения в стеке, затем отобразите в TextView при нажатии кнопки - PullRequest
0 голосов
/ 14 апреля 2020

Я работаю над калькулятором, и мне нужно сохранять каждое нажатие кнопки в стеке, а затем, когда нажимается равная кнопка ("="), мне нужно отобразить эти значения в TextView, а затем сбросить стек, чтобы он был пустым , В настоящее время я могу хранить значения чисел c в стеке, но не могу сохранить знаки ("+ - * /") в стеке в порядке их нажатия.

Я пытаюсь сохранить значения внутри стека и отобразить их в historyView.

MainActivity

package com.example.calculator;

import java.text.DecimalFormat;
import java.util.Stack;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity implements OnClickListener {

    Stack<String> stack = new Stack<String>();

    //    The  gear icon on the top to load the settings page
    ImageButton btnSettings;

    //    Variables for the textviews, etc.
    private TextView calcDisplay;
    public TextView historyView;
    private Boolean userInput = false;
    private CalculatorFunctions CalcBrain;
    private static final String DIGITS = "0123456789.";
    DecimalFormat df = new DecimalFormat("@####");
    Button btnBS;

    //@SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        CalcBrain = new CalculatorFunctions();
        calcDisplay = (TextView) findViewById(R.id.textView1);
        historyView = (TextView) findViewById(R.id.infoTextView);


        /*
         * Control the settings button
         * Starts the new intent which loads in the settings screen
         * */
        btnSettings = (ImageButton) findViewById(R.id.btnSettings);
        btnSettings.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(), SettingsActivity.class);
                startActivity(intent);
            }
        });

//        Sets the decimal amount
        df.setMinimumFractionDigits(0);
        df.setMinimumIntegerDigits(1);
        df.setMaximumIntegerDigits(8);

        /*
         * Checks if the orientation is landscape
         * Adds the onClickListeners to the buttons
         * */
        int orientation = getResources().getConfiguration().orientation;
        if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
            findViewById(R.id.button0).setOnClickListener(this);
            findViewById(R.id.button1).setOnClickListener(this);
            findViewById(R.id.button2).setOnClickListener(this);
            findViewById(R.id.button3).setOnClickListener(this);
            findViewById(R.id.button4).setOnClickListener(this);
            findViewById(R.id.button5).setOnClickListener(this);
            findViewById(R.id.button6).setOnClickListener(this);
            findViewById(R.id.button7).setOnClickListener(this);
            findViewById(R.id.button8).setOnClickListener(this);
            findViewById(R.id.button9).setOnClickListener(this);
            findViewById(R.id.buttonAdd).setOnClickListener(this);
            findViewById(R.id.buttonSubtract).setOnClickListener(this);
            findViewById(R.id.buttonMultiply).setOnClickListener(this);
            findViewById(R.id.buttonDivide).setOnClickListener(this);
            findViewById(R.id.buttonToggleSign).setOnClickListener(this);
            findViewById(R.id.buttonDecimalPoint).setOnClickListener(this);
            findViewById(R.id.buttonEquals).setOnClickListener(this);
            findViewById(R.id.buttonClear).setOnClickListener(this);
            findViewById(R.id.buttonClearMemory).setOnClickListener(this);
            findViewById(R.id.buttonAddToMemory).setOnClickListener(this);
            findViewById(R.id.buttonSubtractFromMemory).setOnClickListener(this);
            findViewById(R.id.buttonRecallMemory).setOnClickListener(this);
            findViewById(R.id.buttonBackspace).setOnClickListener(this);
            findViewById(R.id.buttonSin).setOnClickListener(this);
            findViewById(R.id.buttonCos).setOnClickListener(this);
            findViewById(R.id.buttonTan).setOnClickListener(this);
            findViewById(R.id.buttonSquare).setOnClickListener(this);
            findViewById(R.id.buttonSquareRoot).setOnClickListener(this);
        } else {
            findViewById(R.id.button0).setOnClickListener(this);
            findViewById(R.id.button1).setOnClickListener(this);
            findViewById(R.id.button2).setOnClickListener(this);
            findViewById(R.id.button3).setOnClickListener(this);
            findViewById(R.id.button4).setOnClickListener(this);
            findViewById(R.id.button5).setOnClickListener(this);
            findViewById(R.id.button6).setOnClickListener(this);
            findViewById(R.id.button7).setOnClickListener(this);
            findViewById(R.id.button8).setOnClickListener(this);
            findViewById(R.id.button9).setOnClickListener(this);
            findViewById(R.id.buttonAdd).setOnClickListener(this);
            findViewById(R.id.buttonSubtract).setOnClickListener(this);
            findViewById(R.id.buttonMultiply).setOnClickListener(this);
            findViewById(R.id.buttonDivide).setOnClickListener(this);
            findViewById(R.id.buttonToggleSign).setOnClickListener(this);
            findViewById(R.id.buttonDecimalPoint).setOnClickListener(this);
            findViewById(R.id.buttonEquals).setOnClickListener(this);
            findViewById(R.id.buttonClear).setOnClickListener(this);
            findViewById(R.id.buttonClearMemory).setOnClickListener(this);
            findViewById(R.id.buttonAddToMemory).setOnClickListener(this);
            findViewById(R.id.buttonSubtractFromMemory).setOnClickListener(this);
            findViewById(R.id.buttonRecallMemory).setOnClickListener(this);
            findViewById(R.id.buttonBackspace).setOnClickListener(this);

        }


        btnBS = findViewById(R.id.buttonBackspace);

        btnBS.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (calcDisplay.getText().length() > 0) {
                    CharSequence currentText = calcDisplay.getText();
                    calcDisplay.setText(currentText.subSequence(0, currentText.length() - 1));
                } else {
                    calcDisplay.setText("");
                }
            }
        });

    }

    /*
    * I'm trying to save the value to the stack inside of here
    * */
    @Override
    public void onClick(View v) {
        String buttonPressed = ((Button) v).getText().toString();
        if (DIGITS.contains(buttonPressed)) { // digit was pressed
            if (userInput) {
                if (buttonPressed.equals(".") && calcDisplay.getText().toString().contains(".")) {
                } else {
                    calcDisplay.append(buttonPressed);
                    stack.add(buttonPressed);
                }
            } else {
                if (buttonPressed.equals(".")) {
                    calcDisplay.setText(0 + buttonPressed);
                    stack.add(buttonPressed);
                } else {
                    calcDisplay.setText(buttonPressed);
                    stack.add(buttonPressed);
                }
                userInput = true;
            }
            historyView.setText(null);
        } else { // operation was pressed
            if (userInput) {
                CalcBrain.setOperand(Double.parseDouble(calcDisplay.getText().toString()));

                userInput = false;
            }
            stack.add(CalcBrain.getOperand());
            CalcBrain.instantCalculatorOperation(buttonPressed);
            calcDisplay.setText(df.format(CalcBrain.getResult()));
            historyView.setText(null);
        }
        System.out.println(stack.toString());
        historyView.setText(null);
        historyView.setText(stack.toString());
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState); // Save variables on screen orientation change
        outState.putDouble("OPERAND", CalcBrain.getResult());
        outState.putDouble("MEMORY", CalcBrain.getMemory());
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState); // Restore variables on screen orientation change
        CalcBrain.setOperand(savedInstanceState.getDouble("OPERAND"));
        CalcBrain.setMemory(savedInstanceState.getDouble("MEMORY"));
        calcDisplay.setText(df.format(CalcBrain.getResult()));
    }
}

CalculatorFunctions

package com.example.calculator;

public class CalculatorFunctions {
    private double operand;
    private double memOperand;
    private String memOperator;
    private double calcMemory;
    private static final String add = "+";
    private static final String subtract = "-";
    private static final String multiply = "*";
    private static final String divide = "/";
    private static final String clear = "C";
    private static final String memoryClear = "MC";
    private static final String memoryAdd = "M+";
    private static final String memorySubtract = "M-";
    private static final String memoryRecall = "MR";
    private static final String squareRoot = "√";
    private static final String squared = "x²";
    private static final String invert = "1/x";
    private static final String signToggle = "+/-";
    private static final String sine = "sin";
    private static final String cosine = "cos";
    private static final String tangent = "tan";
    public static final String equal = "=";

    MainActivity ma = new MainActivity();
    public String inputOp = "";

    public CalculatorFunctions() {
        operand = 0;
        memOperand = 0;
        memOperator = "";
        calcMemory = 0;
    }

    public void setOperand(double operand) {
        this.operand = operand;
    }

    public String getOperand() {

        return memOperator;
    }

    public double getResult() {
        return operand;
    }

    public void setMemory(double calculatorMemory) {
        calcMemory = calculatorMemory;
    }

    public double getMemory() {
        return calcMemory;
    }

    public String toString() {
        return Double.toString(operand);
    }

    protected double instantCalculatorOperation(String operator) {

        if (operator.equals(clear)) {
            operand = 0;
            memOperator = "";
            memOperand = 0; //
            calcMemory = 0;
            //ma.historyView.setText(null);
        } else if (operator.equals(memoryClear)) {
            calcMemory = 0;
        } else if (operator.equals(memoryAdd)) {
            calcMemory = calcMemory + operand;
        } else if (operator.equals(memorySubtract)) {
            calcMemory = calcMemory - operand;
        } else if (operator.equals(memoryRecall)) {
            operand = calcMemory;
        } else if (operator.equals(squareRoot)) {
            ma.stack.add(squareRoot);
            operand = Math.sqrt(operand);
        } else if (operator.equals(squared)) {
            ma.stack.add(squared);
            operand = operand * operand;
        } else if (operator.equals(invert)) {
            if (operand != 0) {
                operand = 1 / operand;
            }
        } else if (operator.equals(signToggle)) {
            operand = -operand;
        } else if (operator.equals(sine)) {
            ma.stack.add(sine);
            operand = Math.sin(Math.toRadians(operand));
            Math.toRadians(operand);
        } else if (operator.equals(cosine)) {
            ma.stack.add(cosine);
            operand = Math.cos(Math.toRadians(operand));
            Math.toRadians(operand);
        } else if (operator.equals(tangent)) {
            ma.stack.add(tangent);
            operand = Math.tan(Math.toRadians(operand));
            Math.toRadians(operand);
        } else {
            calculatorOperation();
            System.out.println(memOperator);
            memOperator = operator;
            memOperand = operand;
        }
        return operand;
    }


    protected void calculatorOperation() {

        if (memOperator.equals(add)) {
            operand = memOperand + operand;
            inputOp = memOperator;
            //System.out.println(inputOp);
            ma.stack.add(inputOp);
        } else if (memOperator.equals(subtract)) {
            inputOp = subtract;
            //System.out.println(inputOp);
            ma.stack.add(subtract);
            operand = memOperand - operand;
        } else if (memOperator.equals(multiply)) {
            inputOp = multiply;
            //System.out.println(inputOp);
            ma.stack.add(multiply);
            operand = memOperand * operand;
        } else if (memOperator.equals(divide)) {
            if (operand != 0) {
                inputOp = divide;
                //System.out.println(inputOp);
                operand = memOperand / operand;
                ma.stack.add(divide);
            }
        }
    }

}

Activity_main. xml - При необходимости

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/functionPad"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:orientation="vertical"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingBottom="@dimen/activity_vertical_margin">

    <LinearLayout
        android:id="@+id/rowInfo"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight=".14">

        <ImageButton
            android:id="@+id/btnSettings"
            android:layout_width="56dp"
            android:layout_height="42dp"
            android:scaleType="fitCenter"
            android:src="@drawable/settingsicon"
            android:visibility="visible" />

        <TextView
            android:id="@+id/infoTextView"
            android:layout_width="313dp"
            android:layout_height="match_parent"
            android:gravity="right"
            android:maxLines="1"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textSize="40sp" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/row1"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_weight=".14">

        <TextView
            android:id="@+id/textView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="right"
            android:maxLines="1"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            android:text="0"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textSize="40sp" />
    </LinearLayout>

<LinearLayout
    android:id="@+id/row2"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight=".12">

    <Button
        android:id="@+id/buttonClearMemory"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight=".25"
        android:text="@string/buttonClearMemory"
        android:textSize="25sp"
        android:textColor="@color/black"
        app:backgroundTint="@color/offWhite"
        />

    <Button
        android:id="@+id/buttonAddToMemory"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight=".25"
        android:text="@string/buttonAddToMemory"
        android:textSize="25sp"
        android:textColor="@color/black"
        app:backgroundTint="@color/offWhite"
        />

    <Button
        android:id="@+id/buttonSubtractFromMemory"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight=".25"
        android:text="@string/buttonSubtractFromMemory"
        android:textSize="25sp"
        android:textColor="@color/black"
        app:backgroundTint="@color/offWhite"
        />

    <Button
        android:id="@+id/buttonRecallMemory"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight=".25"
        android:text="@string/buttonRecallMemory"
        android:textSize="25sp"
        android:textColor="@color/black"
        app:backgroundTint="@color/offWhite"
        />
</LinearLayout>

<LinearLayout
    android:id="@+id/row3"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight=".12">

    <Button
        android:id="@+id/buttonClear"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight=".25"
        android:text="@string/buttonClear"
        android:textSize="25sp"
        android:textColor="@color/black"
        app:backgroundTint="@color/offWhite"
        />

    <Button
        android:id="@+id/buttonToggleSign"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight=".25"
        android:text="@string/buttonToggleSign"
        android:textSize="25sp"
        android:textColor="@color/black"
        app:backgroundTint="@color/offWhite"
        />

    <Button
        android:id="@+id/buttonDivide"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight=".25"
        android:text="@string/buttonDivide"
        android:textSize="25sp"
        android:textColor="@color/black"
        app:backgroundTint="@color/offWhite"
        />

    <Button
        android:id="@+id/buttonMultiply"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight=".25"
        android:text="@string/buttonMultiply"
        android:textSize="25sp"
        android:textColor="@color/black"
        app:backgroundTint="@color/offWhite"
        />

</LinearLayout>

<LinearLayout
    android:id="@+id/row4"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight=".12">

    <Button
        android:id="@+id/button7"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight=".25"
        android:text="@string/button7"
        android:textSize="25sp"
        android:textColor="@color/black"
        app:backgroundTint="@color/offWhite"
        />

    <Button
        android:id="@+id/button8"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight=".25"
        android:text="@string/button8"
        android:textSize="25sp"
        android:textColor="@color/black"
        app:backgroundTint="@color/offWhite"
        />

    <Button
        android:id="@+id/button9"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight=".25"
        android:text="@string/button9"
        android:textSize="25sp"
        android:textColor="@color/black"
        app:backgroundTint="@color/offWhite"
        />

    <Button
        android:id="@+id/buttonSubtract"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight=".25"
        android:text="@string/buttonSubtract"
        android:textSize="25sp"
        android:textColor="@color/black"
        app:backgroundTint="@color/offWhite"
        />
</LinearLayout>

<LinearLayout
    android:id="@+id/row5"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight=".12">

    <Button
        android:id="@+id/button4"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight=".25"
        android:text="@string/button4"
        android:textSize="25sp"
        android:textColor="@color/black"
        app:backgroundTint="@color/offWhite"
        />

    <Button
        android:id="@+id/button5"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight=".25"
        android:text="@string/button5"
        android:textSize="25sp"
        android:textColor="@color/black"
        app:backgroundTint="@color/offWhite"
        />

    <Button
        android:id="@+id/button6"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight=".25"
        android:text="@string/button6"
        android:textSize="25sp"
        android:textColor="@color/black"
        app:backgroundTint="@color/offWhite"
        />

    <Button
        android:id="@+id/buttonAdd"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight=".25"
        android:text="@string/buttonAdd"
        android:textSize="25sp"
        android:textColor="@color/black"
        app:backgroundTint="@color/offWhite"
        />
</LinearLayout>

<LinearLayout
    android:id="@+id/row6"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight=".24"
    android:baselineAligned="false">

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight=".75"
        android:orientation="vertical">

        <LinearLayout
            android:id="@+id/linearLayout1"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight=".50"
            android:textSize="25sp">

            <Button
                android:id="@+id/button1"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight=".33"
                android:text="@string/button1"
                android:textSize="25sp"
                android:textColor="@color/black"
                app:backgroundTint="@color/offWhite"
                />

            <Button
                android:id="@+id/button2"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight=".33"
                android:text="@string/button2"
                android:textSize="25sp"
                android:textColor="@color/black"
                app:backgroundTint="@color/offWhite"
                />

            <Button
                android:id="@+id/button3"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight=".34"
                android:text="@string/button3"
                android:textSize="25sp"
                android:textColor="@color/black"
                app:backgroundTint="@color/offWhite"
                />
        </LinearLayout>

        <LinearLayout
            android:id="@+id/linearLayout2"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight=".50">

            <Button
                android:id="@+id/button0"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight=".34"
                android:text="@string/button0"
                android:textSize="25sp"
                android:textColor="@color/black"
                app:backgroundTint="@color/offWhite"
                />

            <Button
                android:id="@+id/buttonDecimalPoint"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight=".34"
                android:text="@string/buttonDecimalPoint"
                android:textSize="25sp"
                android:textColor="@color/black"
                app:backgroundTint="@color/offWhite"
                />

            <Button
                android:id="@+id/buttonBackspace"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight=".34"
                android:text="Back Space"
                android:textColor="@color/black"
                app:backgroundTint="@color/offWhite"
                />

        </LinearLayout>
    </LinearLayout>

    <Button
        android:id="@+id/buttonEquals"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight=".25"
        android:text="@string/buttonEquals"
        android:textSize="25sp"
        style="@style/Widget.AppCompat.Button.Colored"
        />
</LinearLayout>

</LinearLayout>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...