Простейший калькулятор 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.

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.

Источник

popin

Необходимо написать простой консольный калькулятор на Java.

Для считывания ввода нужно использовать класс Scanner.

Scanner позволяет считывать строки и числа:

Scanner scanner = new Scanner(System.in);

int operand1 = scanner.nextInt(); //считывает число

/* Метод next() класса Scanner считывает строку,

а метод charAt(0) позволяет взять первый символ в этой строке.

так мы получаем операцию, которую нужно выполнить*/

char operation = scanner.next().charAt(0);

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

в конце напечатать результат.

Ответьте на следующие вопросы прежде чем приступить к написанию кода:

1. Какой оператор лучше использовать, чтобы проверить, какую операцию выполнять? (switch)

2. Если пользователь ввёл не поддерживаемую операцию стоит ли ему сообщить об этом? ( проверка ввода .. предупредить об ошибке)

3. Нужна ли дополнительная переменная для второго операнда? А для результата? (operand2 для второго и result для результата)

4. Можно ли написать весь код в одном методе? или вынести код для каждой операции отдельно? (лучше разнести получение одного, второго операнда и знака операции отдельно, и отдельный метод для расчета)

прежде чем решать данную задачу, необходимо разбить задачу на подзадачи. всего есть 3 основных шага:

Шаг №1 вводятся 2 числа ->> метод getInt()

Шаг №2 выбирается операция ->> метод char getOperation()

Шаг №3 Калькулятор считает ->> метод int calc(int operand1, int operand2, char operation)

поэтому в методе int nextInt() мы прописали механику считывания числа с консоли и проверки целочисленное число введено или нет.

public static int nextInt() System.out.println("Введите число:");
int operand;
if(scanner.hasNextInt()) operand = scanner.nextInt();
> else System.out.println("Вы допустили ошибку при вводе числа. Попробуйте еще раз.");
scanner.next();//рекурсия
operand = nextInt();
>
return operand;
>

и потом просто в методе main() вызовем 2 раза метод int nextInt(),

потому что пользователь будет вводить 2 числа.

Обратите внимание, что с помощью конструкции if-else мы прописали, что если число целочисленное, тогда присвоить введенное пользователем значение в переменную operand, если же не целочисленное, — вывести в консоль «Вы допустили ошибку при вводе числа. Попробуйте еще раз».

Также обратите внимание, что мы использовали рекурсию в else:

> else System.out.println("Вы допустили ошибку при вводе числа. Попробуйте еще раз.");
scanner.next();//рекурсия
operand = nextInt();
>

Выбо операции (+ — * /) мы осуществили с помощью метода char getOperation()

public static char getOperation() System.out.println("Введите операцию:");
char operation;
if(scanner.hasNext()) operation = scanner.next().charAt(0);
> else System.out.println("Вы допустили ошибку при вводе операции. Попробуйте еще раз.");
scanner.next();//рекурсия
operation = getOperation();
>
return operation;
>

Как видите, пользователю предлагается ввести операцию. А далее программа должна распознать было ли введеное пользователем значение типа char или нет. Причем нас устроит только, если пользователь введет: + — * или / . Например, если пользователь введет число, нас не устроит. Вероно? Поэтому мы применили небольшую хитрость вот в этих 2 строчках кода:

if(scanner.hasNext()) operation = scanner.next().charAt(0);

Мы с помощью метода сканера next() считали всю строчку. А далее, поскольку нам не нужна вся строка, а нужен только первый элемент строки, то есть нулевой элемент, поэтому мы вызвали еще и метод charAt(0). И таким образом мы получим только значение 0-го элемента, а не всей строки.

И далее мы прописали сам метод int calc(int operand1, int operand2, int operation):

public static int calc(int operand1, int operand2, char operation) int result;
switch (operation) case '+':
result = operand1+operand2;
break;
case '-':
result = operand1-operand2;
break;
case '*':
result = operand1*operand2;
break;
case '/':
result = operand1/operand2;
break;
default:
System.out.println("Операция не распознана. Повторите ввод.");
result = calc(operand1, operand2, getOperation());//рекурсия
>
return result;
>

Как видите, мы использовали конструкцию switch-case. И прописали, что:

если пользователь ввел +, тогда operand1+operand2, то есть суммируем 2 числа, введенных пользователем.

если пользовательввел -, тогда operand1-operand2, то есть из 1-го числа, введенного пользователем вычитаем 2-е число

также обратите внимание, что здесь мы тоже использовали рекурсию.

 default: 
System.out.println("Операция не распознана. Повторите ввод.");
result = calc(operand1, operand2, getOperation());//рекурсия

и после того как мы прописали все необходимые методы, мы в методе main() прописали следующее:

public static void main(String[] args) int operand1 = nextInt();
int operand2 = nextInt();
char operation = getOperation();
int result = calc(operand1,operand2,operation);
System.out.println("Результат операции: "+result);
>

то есть в переменные operand1 и operand2 будут присвоены,

соответственно, 1-е и 2-е число, введенное пользователем.

в переменнную operation будет присвоенна операция, которую ввел пользователь: + — * или /

далее в переменную result будет присвоен рузультат вычислений нашего калькулятора

и после этого результат будет выведен в консоль

ниже приведем весь код калькулятора

import java.util.Scanner;

public class Calculator static Scanner scanner = new Scanner(System.in);

public static void main(String[] args) int operand1 = nextInt();
int operand2 = nextInt();
char operation = getOperation();
int result = calc(operand1,operand2,operation);
System.out.println("Результат операции: "+result);
>

public static int nextInt() System.out.println("Введите число:");
int operand;
if(scanner.hasNextInt()) operand = scanner.nextInt();
> else System.out.println("Вы допустили ошибку при вводе числа. Попробуйте еще раз.");
scanner.next();//рекурсия
operand = nextInt();
>
return operand;
>

public static char getOperation() System.out.println("Введите операцию:");
char operation;
if(scanner.hasNext()) operation = scanner.next().charAt(0);
> else System.out.println("Вы допустили ошибку при вводе операции. Попробуйте еще раз.");
scanner.next();//рекурсия
operation = getOperation();
>
return operation;
>

public static int calc(int operand1, int operand2, char operation) int result;
switch (operation) case '+':
result = operand1+operand2;
break;
case '-':
result = operand1-operand2;
break;
case '*':
result = operand1*operand2;
break;
case '/':
result = operand1/operand2;
break;
default:
System.out.println("Операция не распознана. Повторите ввод.");
result = calc(operand1, operand2, getOperation());//рекурсия
>
return result;
>
>

Источник

Java Guides

In this tutorial, we’ll implement a very simple calculator in Java supporting addition, subtraction, multiplication, and division operations.

We’ll also take the operator and operands as inputs and process the calculations based on them.

This tutorial is useful for beginners to understand how to build a very simple calculator using Core Java.

We will use the Scanner class to read user inputs such as operator, number 1, and number 2.

We will make a simple calculator using if-else as well as switch-case statement:

Simple calculator using if-else in Java

package com.java.calculator; import java.util.InputMismatchException; import java.util.Scanner; public class BasicCalculatorIfElse < public static void main(String[] args) < System.out.println("---------------------------------- \n" + "Welcome to Basic Calculator \n" + "----------------------------------"); System.out.println("Following operations are supported : \n" + "1. Addition (+) \n" + "2. Subtraction (-) \n" + "3. Multiplication (* OR x) \n" + "4. Division (/) \n"); try(Scanner scanner = new Scanner(System.in)) < System.out.println("Enter an operator: (+ OR - OR * OR /) "); char operation = scanner.next().charAt(0); if (!(operation == '+' || operation == '-' || operation == '*' || operation == 'x' || operation == '/')) < System.err.println("Invalid Operator. Please use only + or - or * or /"); >System.out.println("Enter First Number: "); double num1 = scanner.nextDouble(); System.out.println("Enter Second Number: "); double num2 = scanner.nextDouble(); if (operation == '/' && num2 == 0.0) < System.err.println("Second Number cannot be zero for Division operation."); >if (operation == '+') < System.out.println(num1 + " + " + num2 + " = " + (num1 + num2)); >else if (operation == '-') < System.out.println(num1 + " - " + num2 + " = " + (num1 - num2)); >else if (operation == '*' || operation == 'x') < System.out.println(num1 + " x " + num2 + " = " + (num1 * num2)); >else if (operation == '/') < System.out.println(num1 + " / " + num2 + " = " + (num1 / num2)); >else < System.err.println("Invalid Operator Specified."); >> catch (InputMismatchException exc) < System.err.println(exc.getMessage()); >> > 

Output :

---------------------------------- Welcome to Basic Calculator ---------------------------------- Following operations are supported : 1. Addition (+) 2. Subtraction (-) 3. Multiplication (* OR x) 4. Division (/) Enter an operator: (+ OR - OR * OR /) + Enter First Number: 10 Enter Second Number: 20 10.0 + 20.0 = 30.0

Simple calculator using switch case in Java

package com.java.calculator; import java.util.InputMismatchException; import java.util.Scanner; public class BasicCalculator < public static void main(String[] args) < System.out.println("---------------------------------- \n" + "Welcome to Basic Calculator \n" + "----------------------------------"); System.out.println("Following operations are supported : \n" + "1. Addition (+) \n" + "2. Subtraction (-) \n" + "3. Multiplication (* OR x) \n" + "4. Division (/) \n"); try (Scanner scanner = new Scanner(System.in)) < System.out.println("Enter an operator (+, -, *, /):"); char operation = scanner.next().charAt(0); if (!(operation == '+' || operation == '-' || operation == '*' || operation == 'x' || operation == '/')) < System.err.println("Invalid Operator. Please use only + or - or * or /"); >System.out.println("Enter First Number: "); double num1 = scanner.nextDouble(); System.out.println("Enter Second Number: "); double num2 = scanner.nextDouble(); if (operation == '/' && num2 == 0.0) < System.err.println("Second Number cannot be zero for Division operation."); >switch (operation) < case '+': System.out.println(num1 + " + " + num2 + " = " + (num1 + num2)); break; case '-': System.out.println(num1 + " - " + num2 + " = " + (num1 - num2)); break; case '*': System.out.println(num1 + " x " + num2 + " = " + (num1 * num2)); break; case 'x': System.out.println(num1 + " x " + num2 + " = " + (num1 * num2)); break; case '/': System.out.println(num1 + " / " + num2 + " = " + (num1 / num2)); break; default: System.err.println("Invalid Operator Specified."); break; >> catch (InputMismatchException exc) < System.err.println(exc.getMessage()); >> > 

Output :

---------------------------------- Welcome to Basic Calculator ---------------------------------- Following operations are supported : 1. Addition (+) 2. Subtraction (-) 3. Multiplication (* OR x) 4. Division (/) Enter an operator (+, -, *, /): - Enter First Number: 20 Enter Second Number: 10 20.0 - 10.0 = 10.0

Источник

Читайте также:  Python read russian txt
Оцените статью