Создаем калькулятор на java

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Calculator console application in Java

OpenGenus/calculator-in-java

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Читайте также:  Django template tag html

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Calculator Console Application

This is a simple calculator application that takes a mathematical expression as input and evaluates it. The application is written in Java and has two main files: main.java and helper.java .

This file contains the main function, which takes input from the user, calls the evaluate method from the Helper class, and prints the result.

This file contains the methods evaluate , hasPrecedence , and applyOp .

The evaluate method takes a string input and evaluates it as a mathematical expression using the Shunting Yard algorithm. It uses two stacks, one for operands and one for operators. The method converts the input string from infix notation to postfix notation and then evaluates it.

hasPrecedence(char op1, char op2)

The hasPrecedence method compares the precedence of two operators, op1 and op2 . It returns true if op1 has higher or equal precedence than op2 , and false otherwise. This method is used in the evaluate method to ensure that the operators are applied in the correct order.

applyOp(char op, double b, double a)

The applyOp method takes an operator, op , and two operands, a and b , and applies the operator to the operands. It returns the result of the operation. This method is used in the evaluate method to apply the operators to the operands.

  1. Clone the repository git clone https://github.com/OpenGenus/calculator-in-java.git
  2. Open the project in your preferred IDE
  3. Compile and run the main.java file
  4. Input the mathematical expression you want to evaluate
  5. The result will be displayed on the console

Note: The calculator only supports basic arithmetic operations such as addition, subtraction, multiplication, and division. It also supports the use of parentheses.

For the full explanation of the project, visit the link.

Источник

Как создать калькулятор на Java — полное руководство с кодом

В этом руководстве мы расскажем, как создать калькулятор на Java для Android. Если вы новичок в программировании и никогда раньше не создавали приложения, ознакомьтесь с нашим предыдущим руководством по написанию первого приложения для Android:

Предполагается, что у вас есть хотя бы минимальный базовый опыт создания Android – приложений .

Полный исходный код калькулятора, описанного ниже, доступен для использования и изменения на github .

Создание проекта

Первое, что нужно сделать — это создать в Android Studio новый проект: Start a new Android Studio project или File — New — New Project :

Создание проекта

Для этого руководства мы выбрали в панели « Add an Activity to Mobile » опцию « EmptyActivity », для « MainActivity » мы оставили имя по умолчанию – « Activity ». На этом этапе структура должна выглядеть, как показано на рисунке ниже. У вас есть MainActivity внутри пакета проекта и файл activity_main.xml в папке layout :

Создание проекта - 2

Включение привязки данных в проекте

Перед тем, как создать приложение для Андроид с нуля, нужно уяснить, что использование привязки данных помогает напрямую обращаться к виджетам ( Buttons , EditText и TextView ), а не находить их с помощью методов findViewById() . Чтобы включить привязку данных, добавить следующую строку кода в файл build.gradle .

Включение привязки данных в проекте

Разработка макета калькулятора

Для включения привязки данных в файле activity_main.xml требуется еще одно изменение. Оберните сгенерированный корневой тег ( RelativeLayout ) в layout , таким образом сделав его новым корневым тегом.

Как научиться создавать приложения для Андроид? Читайте наше руководство дальше.

Тег layout — это предупреждает систему построения приложения, что этот файл макета будет использовать привязку данных. Затем система генерирует для этого файла макета класс Binding . Поскольку целевой XML-файл называется activity_main.xml , система построения приложения создаст класс ActivityMainBinding , который можно использовать в приложении, как и любой другой класс Java . Имя класса составляется из имени файла макета, в котором каждое слово через подчеркивание будет начинаться с заглавной буквы, а сами подчеркивания убираются, и к имени добавляется слово « Binding ».

Теперь перейдите к файлу MainActivity.java . Создайте закрытый экземпляр ActivityMainBinding внутри вашего класса, а в методе onCreate() удалите строку setContentView () и вместо нее добавьте DataBindingUtil.setContentView() , как показано ниже.

public class MainActivity extends AppCompatActivity < private ActivityMainBinding binding; @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); binding = DataBindingUtil.setContentView(this, R.layout.activity_main); >>

Общие принципы создания виджетов макета

В приложении калькулятора есть четыре основных элемента:

RelativeLayout — определяет, как другие элементы будут укладываться или отображаться на экране. RelativeLayout используется для позиционирования дочерних элементов по отношению друг к другу или к самим себе.

TextView — элемент используется для отображения текста. Пользователи не должны взаимодействовать с этим элементом. С помощью TextView отображается результат вычислений.

EditText — похож на элемент TextView, с той лишь разницей, что пользователи могут взаимодействовать с ним и редактировать текст. Но поскольку калькулятор допускает только фиксированный набор вводимых данных, мы устанавливаем для него статус « не редактируемый ». Когда пользователь нажимает на цифры, мы выводим их в EditText .

Button — реагирует на клики пользователя. При создании простого приложения для Андроид мы используем кнопки для цифр и операторов действий в калькуляторе.

Создание макета калькулятора

Создание макета калькулятора

Код макета калькулятора объемный. Это связано с тем, что мы должны явно определять и тщательно позиционировать каждую из кнопок интерфейса. Ниже представлен фрагмент сокращенной версии файла макета activity_main :

Внутренние компоненты калькулятора

Перед тем, как создать приложение на телефон Android , отметим, что valueOne и valueTwo содержат цифры, которые будут использоваться. Обе переменные имеют тип double , поэтому могут содержать числа с десятичными знаками и без них. Мы устанавливаем для valueOne специальное значение NaN ( не число ) — подробнее это будет пояснено ниже.

private double valueOne = Double.NaN; private double valueTwo;

Этот простой калькулятор сможет выполнять только операции сложения, вычитания, умножения и деления. Поэтому мы определяем четыре статических символа для представления этих операций и переменную CURRENT_ACTION , содержащую следующую операцию, которую мы намереваемся выполнить.

private static final char ADDITION = '+'; private static final char SUBTRACTION = '-'; private static final char MULTIPLICATION = '*'; private static final char DIVISION = '/'; private char CURRENT_ACTION;

Затем мы используем класс DecimalFormat для форматирования результата. Конструктор десятичного формата позволяет отображать до десяти знаков после запятой.

decimalFormat = new DecimalFormat("#.##########");

Обработка нажатий на цифры

В нашем создаваемом простом приложении для Андроид всякий раз, когда пользователь нажимает на цифру или точку, нам нужно добавить эту цифру в editText . Пример кода ниже иллюстрирует, как это делается для цифры ноль ( 0 ).

binding.buttonZero.setOnClickListener(new View.OnClickListener() < @Override public void onClick(View view) < binding.editText.setText(binding.editText.getText() + "0"); >>);

Обработка кликов по кнопкам операторов

Обработка кликов по кнопкам операторов

Обработка нажатия кнопок операторов ( действий ) выполняется по-другому. Сначала нужно выполнить все ожидающие в очереди вычисления. Поэтому мы определяем метод computeCalculation . В computeCalculation , если valueOne является допустимым числом, мы считываем valueTwo из editText и выполняем текущие операции в очереди. Если же valueOne является NaN , для valueOne присваивается цифра в editText .

private void computeCalculation() < if(!Double.isNaN(valueOne)) < valueTwo = Double.parseDouble(binding.editText.getText().toString()); binding.editText.setText(null); if(CURRENT_ACTION == ADDITION) valueOne = this.valueOne + valueTwo; else if(CURRENT_ACTION == SUBTRACTION) valueOne = this.valueOne - valueTwo; else if(CURRENT_ACTION == MULTIPLICATION) valueOne = this.valueOne * valueTwo; else if(CURRENT_ACTION == DIVISION) valueOne = this.valueOne / valueTwo; >else < try < valueOne = Double.parseDouble(binding.editText.getText().toString()); >catch (Exception e)<> > >

Продолжаем создавать копию приложения на Андроид . Для каждого оператора мы сначала вызываем computeCalculation() , а затем устанавливаем для выбранного оператора CURRENT_ACTION . Для оператора равно (=) мы вызываем computeCalculation() , а затем очищаем содержимое valueOne и CURRENT_ACTION .

Заключение

Если вы запустите и протестируете данное приложение, то увидите некоторые моменты, которые можно улучшить: 1) возможность нажимать на кнопку оператора, когда editText очищен ( т. е. без необходимости ввода первой цифры ), 2) возможность продолжать вычисления после нажатия кнопки « Равно ».

Полный код примера доступен на github .

Источник

Calculator Program in Java Swing/JFrame with Source Code

Hello friends today we will learn how we can create a Simple Calculator Program in Java Using Swing with Source Code. This is going to be our first application using swing programming. This is going to be a simple Java GUI calculator project which will perform basic arithmetic operations like addition, subtraction, multiplication, division etc. It can also be used for finding the square, square root and reciprocal of any number.

Before starting this tutorial, I assume that you have the basic concept of swing components and also you should have the idea of JButton Click Event means what should be the response of a button when we click on it. If you already know about Basic Components of Java Swing, then it’s not going to be very difficult for you.

I will use NetBeans IDE(integrated development environment) for the coding part of my calculator program. You can use any IDE like IntelliJ IDEA, Eclipse or you can just use notepad++ to code your program. It doesn’t matter whatever IDE or editor you will use the programming logic will be the same.

So friends, lets get started with our tutorial Simple Calculator Program in Java Using Swing or can say simple calculator program in Java using JFrame/frame step by step.

Simple Calculator Program in Java Using Swing

Creating a New Calculator Project in NetBeans

First of all, we need to create a new project in Netbeans. For this, follow these steps.

  • Open the NetBeans IDE and then click on the File menu and then select New Project.

Simple Calculator Program in Java Using Swing

  • After that, a window will be opened. From there, select Java in categories and Java Application in projects and then click on the Next Button.

Simple Calculator Program in Java Using Swing

  • After you click on the Next button again a new window will be opened and there you have to give the name of the Project (Calculator in this Example) and also uncheck the create Main class option.
  • Then click on the Finish Button.

Simple Calculator Program in Java Using Swing

  • Now expand your project using the + icon and right-click on the source packages.
  • Then select new>>Java class.

Simple Calculator Program in Java Using Swing

  • A new window will be opened where you have to give the name of your Java class (Calculator in this Example).
  • Then click on the Finish button.

Creating Display Window for Calculator

Now we will create a display window or frame for our calculator.

  • Create an object of the JFrame class and set some of its properties like its title, visibility, background color, layout property etc. using the method of the JFrame class.

Источник

Оцените статью