Как написать программу калькулятор на 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.

JAVA

android {
    ...
    dataBinding.enabled = true
    ...

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

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

XML

<?xml version="1.0" encoding="utf-8"?>
<layout>
    <RelativeLayout>
    ...
    </RelativeLayout>
</layout>

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

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

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

JAVA

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:

<layout>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/activity_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        tools:context="com.sample.foo.samplecalculator.MainActivity">

        <TextView
            android:id="@+id/infoTextView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="30dp"
            android:textSize="30sp" />

        <EditText
            android:id="@+id/editText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/infoTextView"
            android:enabled="false"
            android:gravity="bottom"
            android:lines="2"
            android:maxLines="2"
            android:textSize="20sp" />

        <Button
            android:id="@+id/buttonSeven"
            style="@style/Widget.AppCompat.Button.Borderless"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/editText"
            android:text="7"
            android:textSize="20sp" />

        <Button
            android:id="@+id/buttonEight"
            style="@style/Widget.AppCompat.Button.Borderless"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/editText"
            android:layout_toRightOf="@id/buttonSeven"
            android:text="8"
            android:textSize="20sp" />

        <Button
            android:id="@+id/buttonNine"
            style="@style/Widget.AppCompat.Button.Borderless"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/editText"
            android:layout_toRightOf="@id/buttonEight"
            android:text="9"
            android:textSize="20sp" />

        ...

        ...

        <Button
            android:id="@+id/buttonDot"
            style="@style/Widget.AppCompat.Button.Borderless"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/buttonOne"
            android:text="."
            android:textSize="20sp" />

        <Button
            android:id="@+id/buttonZero"
            style="@style/Widget.AppCompat.Button.Borderless"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignRight="@id/buttonEight"
            android:layout_below="@id/buttonTwo"
            android:text="0"
            android:textSize="20sp" />

        <Button
            android:id="@+id/buttonEqual"
            style="@style/Widget.AppCompat.Button.Borderless"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignRight="@id/buttonNine"
            android:layout_below="@id/buttonThree"
            android:text="="
            android:textSize="20sp" />

        <Button
            android:id="@+id/buttonDivide"
            style="@style/Widget.AppCompat.Button.Borderless"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignTop="@id/buttonNine"
            android:layout_toRightOf="@id/buttonNine"
            android:text="/"
            android:textSize="20sp" />

        <Button
            android:id="@+id/buttonMultiply"
            style="@style/Widget.AppCompat.Button.Borderless"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignTop="@id/buttonSix"
            android:layout_toRightOf="@id/buttonSix"
            android:text="*"
            android:textSize="20sp" />

        <Button
            android:id="@+id/buttonSubtract"
            style="@style/Widget.AppCompat.Button.Borderless"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignTop="@id/buttonThree"
            android:layout_toRightOf="@id/buttonThree"
            android:text="-"
            android:textSize="20sp" />

        <Button
            android:id="@+id/buttonAdd"
            style="@style/Widget.AppCompat.Button.Borderless"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignTop="@id/buttonEqual"
            android:layout_toRightOf="@id/buttonEqual"
            android:text="+"
            android:textSize="20sp" />

        <Button
            android:id="@+id/buttonClear"
            style="@style/Widget.AppCompat.Button.Borderless"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignRight="@id/buttonAdd"
            android:layout_below="@id/buttonAdd"
            android:layout_marginTop="@dimen/activity_vertical_margin"
            android:text="C"
            android:textSize="20sp" />
    </RelativeLayout>
</layout>

Перед тем, как создать приложение на телефон 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.

JAVA

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.

JAVA

binding.buttonAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                computeCalculation();
                CURRENT_ACTION = ADDITION;
                binding.infoTextView.setText(decimalFormat.format(valueOne) + "+");
                binding.editText.setText(null);
            }
        });
        binding.buttonSubtract.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                computeCalculation();
                CURRENT_ACTION = SUBTRACTION;
                binding.infoTextView.setText(decimalFormat.format(valueOne) + "-");
                binding.editText.setText(null);
            }
        });
        binding.buttonMultiply.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                computeCalculation();
                CURRENT_ACTION = MULTIPLICATION;
                binding.infoTextView.setText(decimalFormat.format(valueOne) + "*");
                binding.editText.setText(null);
            }
        });
        binding.buttonDivide.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                computeCalculation();
                CURRENT_ACTION = DIVISION;
                binding.infoTextView.setText(decimalFormat.format(valueOne) + "/");
                binding.editText.setText(null);
            }
        });
        binding.buttonEqual.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                computeCalculation();
                binding.infoTextView.setText(binding.infoTextView.getText().toString() +
                        decimalFormat.format(valueTwo) + " = " + decimalFormat.format(valueOne));
                valueOne = Double.NaN;
                CURRENT_ACTION = '0';
            }
        });

Поздравляю! Мы завершили создание простого калькулятора. Теперь вы сможете создать приложение для Андроид сами.

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

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

I’m trying to create a basic calculator in Java. I’m quite new to programming so I’m trying to get used to it.

import java.util.Scanner;
import javax.swing.JOptionPane;

public class javaCalculator 
{

    public static void main(String[] args) 
    {
        int num1;
        int num2;
        String operation;


        Scanner input = new Scanner(System.in);

        System.out.println("please enter the first number");
        num1 = input.nextInt();

        System.out.println("please enter the second number");
        num2 = input.nextInt();

        Scanner op = new Scanner(System.in);

        System.out.println("Please enter operation");
        operation = op.next();

        if (operation == "+");
        {
            System.out.println("your answer is" + (num1 + num2));
        }
        if  (operation == "-");
        {
            System.out.println("your answer is" + (num1 - num2));
        }

        if (operation == "/");
        {
            System.out.println("your answer is" + (num1 / num2));
        }
        if (operation == "*")
        {
            System.out.println("your answer is" + (num1 * num2));
        }


    }
}

This is my code. It prompts for the numbers and operation, but displays the answers all together ?

Aruna's user avatar

Aruna

11.9k3 gold badges28 silver badges42 bronze badges

asked Feb 3, 2013 at 18:34

user2037720's user avatar

3

Remove the semi-colons from your if statements, otherwise the code that follows will be free standing and will always execute:

if (operation == "+");
                     ^

Also use .equals for Strings, == compares Object references:

 if (operation.equals("+")) {

answered Feb 3, 2013 at 18:37

Reimeus's user avatar

ReimeusReimeus

158k15 gold badges214 silver badges274 bronze badges

0

Here is simple code for calculator so you can consider this
import java.util.*;
import java.util.Scanner;
public class Hello {
    public static void main(String[] args)
    {
        System.out.println("Enter first and second number:");
        Scanner inp= new Scanner(System.in);
        int num1,num2;
        num1 = inp.nextInt();
        num2 = inp.nextInt();
        int ans;
        System.out.println("Enter your selection: 1 for Addition, 2 for substraction 3 for Multiplication and 4 for division:");
        int choose;
        choose = inp.nextInt();
        switch (choose){
        case 1:
            System.out.println(add( num1,num2));
            break;
        case 2:
            System.out.println(sub( num1,num2));
            break;      
        case 3:
            System.out.println(mult( num1,num2));
            break;
        case 4:
            System.out.println(div( num1,num2));
            break;
            default:
                System.out.println("Illigal Operation");


        }



    }
    public static int add(int x, int y)
    {
        int result = x + y;
        return result;
    }
    public static int sub(int x, int y)
    {
        int result = x-y;
        return result;
    }
    public static int mult(int x, int y)
    {
        int result = x*y;
        return result;
    }
    public static int div(int x, int y)
    {
        int result = x/y;
        return result;
    }

}

answered Sep 20, 2013 at 8:13

Mohamud's user avatar

MohamudMohamud

1321 silver badge3 bronze badges

1

CompareStrings with equals(..) not with ==

if (operation.equals("+")
{
    System.out.println("your answer is" + (num1 + num2));
}
if (operation.equals("-"))
{
    System.out.println("your answer is" + (num1 - num2));
}
if (operation.equals("/"))
{
    System.out.println("your answer is" + (num1 / num2));
}
if (operation .equals( "*"))
{
    System.out.println("your answer is" + (num1 * num2));
}

And the ; after the conditions was an empty statement so the conditon had no effect at all.

If you use java 7 you can also replace the if statements with a switch.
In java <7 you can test, if operation has length 1 and than make a switch for the char [switch (operation.charAt(0))]

answered Feb 3, 2013 at 18:39

MrSmith42's user avatar

MrSmith42MrSmith42

9,7896 gold badges38 silver badges49 bronze badges

import java.util.Scanner;
public class AdditionGame {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    int num1;
    int num2;
    String operation;

    Scanner input = new Scanner(System.in);

    System.out.println("Please Enter The First Number");
    num1 = input.nextInt();

    System.out.println("Please Enter The Second Number");
    num2 = input.nextInt();

    Scanner op = new Scanner (System.in);

    System.out.println("Please Enter The Operation");
    operation = op.next();

    if (operation.equals("+"))
    {
        System.out.println("Your Answer is "+(num1 + num2));
    }
    else if (operation.equals("-"))
    {
        System.out.println("Your Answer is "+(num1 - num2));
    }       
    else if (operation.equals("*"))
    {
        System.out.println("Your Answer is "+(num1 * num2));
    }   
    else if (operation.equals("/"))
    {
        System.out.println("Your Answer is "+(num1 / num2));
    }
}

}

Jagger's user avatar

Jagger

10.3k8 gold badges51 silver badges91 bronze badges

answered Sep 11, 2013 at 20:10

Ronak Mandania's user avatar

1

Java program example for making a simple Calculator:

import java.util.Scanner;

public class Calculator
{
public static void main(String args[])
{
    float a, b, res;
    char select, ch;
    Scanner scan = new Scanner(System.in);

    do
    {
        System.out.print("(1) Additionn");
        System.out.print("(2) Subtractionn");
        System.out.print("(3) Multiplicationn");
        System.out.print("(4) Divisionn");
        System.out.print("(5) Exitnn");
        System.out.print("Enter Your Choice : ");
        choice = scan.next().charAt(0);

        switch(select)
        {
            case '1' : System.out.print("Enter Two Number : ");
                a = scan.nextFloat();
                b = scan.nextFloat();
                res = a + b;
                System.out.print("Result = " + res);
                break;
            case '2' : System.out.print("Enter Two Number : ");
                a = scan.nextFloat();
                b = scan.nextFloat();
                res = a - b;
                System.out.print("Result = " + res);
                break;
            case '3' : System.out.print("Enter Two Number : ");
                a = scan.nextFloat();
                b = scan.nextFloat();
                res = a * b;
                System.out.print("Result = " + res);
                break;
            case '4' : System.out.print("Enter Two Number : ");
                a = scan.nextFloat();
                b = scan.nextFloat();
                res = a / b;
                System.out.print("Result = " + res);
                break;
            case '5' : System.exit(0);
                break;
            default : System.out.print("Wrong Choice!!!");
        }
    }while(choice != 5);       
}
}

answered Apr 10, 2018 at 15:48

Linkon's user avatar

LinkonLinkon

1,0281 gold badge12 silver badges15 bronze badges

maybe its better using the case instead of if dunno if this eliminates the error, but its cleaner i think.. switch (operation){case +: System.out.println("your answer is" + (num1 + num2));break;case -: System.out.println("your answer is" - (num1 - num2));break; ...

answered Feb 3, 2013 at 18:37

Eveli's user avatar

EveliEveli

5081 gold badge6 silver badges27 bronze badges

import java.util.Scanner;
import javax.swing.JOptionPane;

public class javaCalculator
{

public static void main(String[] args) 
{
    int num1;
    int num2;
    String operation;


    Scanner input = new Scanner(System.in);

    System.out.println("please enter the first number");
    num1 = input.nextInt();

    System.out.println("please enter the second number");
    num2 = input.nextInt();

    Scanner op = new Scanner(System.in);

    System.out.println("Please enter operation");
    operation = op.next();

    if (operation.equals("+"))
    {
        System.out.println("your answer is" + (num1 + num2));
    }
   else if  (operation.equals("-"))
    {
        System.out.println("your answer is" + (num1 - num2));
    }

  else if (operation.equals("/"))
    {
        System.out.println("your answer is" + (num1 / num2));
    }
   else if (operation.equals("*"))
    {
        System.out.println("your answer is" + (num1 * num2));
    }
   else 
    {
       System.out.println("Wrong selection");
    }


}

}

answered Apr 10, 2013 at 13:30

Dilip Kumar's user avatar

public class SwitchExample {

    public static void main(String[] args) throws Exception {
        System.out.println(":::::::::::::::::::::Start:::::::::::::::::::");
        System.out.println("nn");

        System.out.println("1. Addition");
        System.out.println("2. Multiplication");
        System.out.println("3. Substraction");
        System.out.println("4. Division");
        System.out.println("0. Exit");
        System.out.println("n");

        System.out.println("Enter Your Choice :::::::  ");
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String str = br.readLine();

        int usrChoice = Integer.parseInt(str);

        switch (usrChoice) {
            case 1:
                doAddition();
                break;
            case 2:
                doMultiplication();
                break;
            case 3:
                doSubstraction();
                break;
            case 4:
                doDivision();
                break;

            case 0:
                System.out.println("Thank you.....");
                break;

            default:
                System.out.println("Invalid Value");
        }

        System.out.println(":::::::::::::::::::::End:::::::::::::::::::");
}

public static void doAddition() throws Exception {
    System.out.println("******* Enter in Addition Process ********");

    String strNo1, strNo2;

    System.out.println("Enter Number 1 For Addition : ");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    strNo1 = br.readLine();

    System.out.println("Enter Number 2 For Addition : ");
    BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
    strNo2 = br1.readLine();

    int no1 = Integer.parseInt(strNo1);
    int no2 = Integer.parseInt(strNo2);

    int result = no1 + no2;

    System.out.println("Addition of " + no1 + " and " + no2 + " is ::::::: " + result);
}

public static void doSubstraction() throws Exception {
    System.out.println("******* Enter in Substraction Process ********");

    String strNo1, strNo2;

    System.out.println("Enter Number 1 For Substraction : ");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    strNo1 = br.readLine();

    System.out.println("Enter Number 2 For Substraction : ");
    BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
    strNo2 = br1.readLine();

    int no1 = Integer.parseInt(strNo1);
    int no2 = Integer.parseInt(strNo2);

    int result = no1 - no2;

    System.out.println("Substraction of " + no1 + " and " + no2 + " is ::::::: " + result);
}

public static void doMultiplication() throws Exception {
    System.out.println("******* Enter in Multiplication Process ********");

    String strNo1, strNo2;

    System.out.println("Enter Number 1 For Multiplication : ");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    strNo1 = br.readLine();

    System.out.println("Enter Number 2 For Multiplication : ");
    BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
    strNo2 = br1.readLine();

    int no1 = Integer.parseInt(strNo1);
    int no2 = Integer.parseInt(strNo2);

    int result = no1 * no2;

    System.out.println("Multiplication of " + no1 + " and " + no2 + " is ::::::: " + result);
}

public static void doDivision() throws Exception {
    System.out.println("******* Enter in Dividion Process ********");

    String strNo1, strNo2;

    System.out.println("Enter Number 1 For Dividion : ");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    strNo1 = br.readLine();

    System.out.println("Enter Number 2 For Dividion : ");
    BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
    strNo2 = br1.readLine();

    int no1 = Integer.parseInt(strNo1);
    int no2 = Integer.parseInt(strNo2);

    float result = no1 / no2;

    System.out.println("Division of " + no1 + " and " + no2 + " is ::::::: " + result);
}

}

LionC's user avatar

LionC

3,1081 gold badge23 silver badges31 bronze badges

answered Oct 8, 2015 at 12:25

Vijay Pansheriya's user avatar

we can simply use in.next().charAt(0); to assign + — * / operations as characters by initializing operation as a char.

import java.util.*;
public class Calculator {

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

char operation;
int num1;
int num2;

 System.out.println("Enter First Number");

num1 = in.nextInt();

System.out.println("Enter Operation");

operation = in.next().charAt(0);

System.out.println("Enter Second Number");

num2 = in.nextInt();

if (operation == '+')//make sure single quotes
{
    System.out.println("your answer is " + (num1 + num2));
}
if (operation == '-')
{
    System.out.println("your answer is " + (num1 - num2));
}
if (operation == '/')
{
    System.out.println("your answer is " + (num1 / num2));
}
if (operation == '*')
{
    System.out.println("your answer is " + (num1 * num2));
}

}

}

answered Jan 9, 2016 at 9:14

ChandWeer's user avatar

ChandWeerChandWeer

1211 silver badge4 bronze badges

import java.util.Scanner;
public class JavaApplication1 {


    public static void main(String[] args) {

         int x,
         int y;

         Scanner input=new Scanner(System.in);
         System.out.println("Enter Number 1");
         x=input.nextInt();
         System.out.println("Enter Number 2");
         y=input.nextInt();

         System.out.println("Please enter operation + - / or *");
         Scanner op=new Scanner(System.in);
         String operation = op.next();

         if (operation.equals("+")){
             System.out.println("Your Answer: " + (x+y));
         }
         if (operation.equals("-")){
             System.out.println("Your Answer: "+ (x-y));
         }
         if (operation.equals("/")){
             System.out.println("Your Answer: "+ (x/y));
         }
         if (operation.equals("*")){
            System.out.println("Your Answer: "+ (x*y));
         }
    }

}

Knells's user avatar

Knells

8272 gold badges12 silver badges24 bronze badges

answered Apr 4, 2016 at 0:48

user6153780's user avatar

1

Данная статья написана командой Vertex Academy. Это одна из статей из нашего «Самоучителя по Java.»


Условие задачи:

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

  • Метод int getInt() — должен считывать с консоли целое число и возвращать его
  • Метод char getOperation() — должен считывать с консоли какое-то значение и возвращать символ с операцией (+, -, * или /)
  • Метод int calc(int num1, int num2, char operation) — должен выполнять над числами num1 и num2 арифметическую операцию, заданную operation.
  • Метод main() — должен считывать 2 числа (с помощью getInt()), считать операцию (с помощью getOperation(), передать все методу calc() и вывести на экран результат.

Решение:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

import java.util.Scanner;

public class Calculator {

    static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {

        int num1 = getInt();

        int num2 = getInt();

        char operation = getOperation();

        int result = calc(num1,num2,operation);

        System.out.println(«Результат операции: «+result);

    }

    public static int getInt(){

        System.out.println(«Введите число:»);

        int num;

        if(scanner.hasNextInt()){

            num = scanner.nextInt();

        } else {

            System.out.println(«Вы допустили ошибку при вводе числа. Попробуйте еще раз.»);

            scanner.next();//рекурсия

            num = getInt();

        }

        return num;

    }

    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 num1, int num2, char operation){

        int result;

        switch (operation){

            case ‘+’:

                result = num1+num2;

                break;

            case ‘-‘:

                result = num1num2;

                break;

            case ‘*’:

                result = num1*num2;

                break;

            case ‘/’:

                result = num1/num2;

                break;

            default:

                System.out.println(«Операция не распознана. Повторите ввод.»);

                result = calc(num1, num2, getOperation());//рекурсия

        }

        return result;

    }

}

Комментарии к задаче:

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

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

public static int getInt(){

    System.out.println(«Введите число:»);

    int num;

    if(scanner.hasNextInt()){

        num = scanner.nextInt();

    } else {

        System.out.println(«Вы допустили ошибку при вводе числа. Попробуйте еще раз.»);

        scanner.next();//рекурсия

        num = getInt();

    }

    return num;

}

  • И потом просто в методе main() вызовем 2 раза метод int getInt(), потому что пользователь будет вводить 2 числа.
  • Обратите внимание, что с помощью конструкции if-else мы прописали, что если число целочисленное, тогда присвоить введенное пользователем значение в переменную num, если же не целочисленное, — вывести в консоль «Вы допустили ошибку при вводе числа. Попробуйте еще раз».
  • Также обратите внимание, что мы использовали рекурсию в else:

    else {

            System.out.println(«Вы допустили ошибку при вводе числа. Попробуйте еще раз.»);

            scanner.next(); //рекурсия

            num = getInt();

        }

Выбор операции (+,-,*,/) мы осуществили с помощью метода 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-го элемента, а не всей строки.

Если вдруг подзабыли как работают методы сканера, перечитайте еще раз вот эту статью — «Работа со сканером в Java».  А также, если необходимо вспомнить как работает метод charAt(), перечитайте вот эту статью — «charAt() в Java»

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

public static int calc(int num1, int num2, char operation){

     int result;

     switch (operation){

         case ‘+’:

             result = num1+num2;

             break;

         case ‘-‘:

             result = num1num2;

             break;

         case ‘*’:

             result = num1*num2;

             break;

         case ‘/’:

             result = num1/num2;

             break;

         default:

             System.out.println(«Операция не распознана. Повторите ввод.»);

             result = calc(num1, num2, getOperation());//рекурсия

      }

      return result;

}

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

  • если пользователь ввел +, тогда num1+num2, то есть суммируем 2 числа, введенных пользователем.
  • если пользователь ввел -, тогда num1-num2, то есть из 1-го числа, введенного пользователем вычитаем 2-е число
  • и т.д.

Если вдруг Вам необходимо вспомнить как работает конструкция switch-case, перечитайте вот эту статью — «Условный оператор if в Java. Оператор switch»

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

default:

             System.out.println(«Операция не распознана. Повторите ввод.»);

             result = calc(num1, num2, getOperation());//рекурсия

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

public static void main(String[] args) {

        int num1 = getInt();

        int num2 = getInt();

        char operation = getOperation();

        int result = calc(num1,num2,operation);

        System.out.println(«Результат операции: «+result);

    }

  • То есть в переменные num1 и num2 будут присвоены, соответственно, 1-е и 2-е число, введенное пользователем.
  • В переменную operation будет присвоена операция, которую ввел пользователь: +, — , * или /
  • Далее в переменную result будет присвоен результат вычислений «нашего калькулятора»
  • И после этого результат будет выведен в консоль

Надеемся — наша статья была Вам полезна. Есть возможность записаться на наши курсы по Java. Детальную информацию смотрите у нас на сайте.

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

//implementing ActionListener interface

public class Calculator implements ActionListener {

   //Creating variables for our calculations

    double number, answer;

    int calculation;

    JFrame frame;

    JLabel label = new JLabel();

    JTextField textField = new JTextField();

    JRadioButton onRadioButton = new JRadioButton(«on»);

    JRadioButton offRadioButton = new JRadioButton(«off»);

    JButton buttonZero = new JButton(«0»);

    JButton buttonOne = new JButton(«1»);

    JButton buttonTwo = new JButton(«2»);

    JButton buttonThree = new JButton(«3»);

    JButton buttonFour = new JButton(«4»);

    JButton buttonFive = new JButton(«5»);

    JButton buttonSix = new JButton(«6»);

    JButton buttonSeven = new JButton(«7»);

    JButton buttonEight = new JButton(«8»);

    JButton buttonNine = new JButton(«9»);

    JButton buttonDot = new JButton(«.»);

    JButton buttonClear = new JButton(«C»);

    JButton buttonDelete = new JButton(«DEL»);

    JButton buttonEqual = new JButton(«=»);

    JButton buttonMul = new JButton(«x»);

    JButton buttonDiv = new JButton(«/»);

    JButton buttonPlus = new JButton(«+»);

    JButton buttonMinus = new JButton(«-«);

    JButton buttonSquare = new JButton(«xu00B2»);

    JButton buttonReciprocal = new JButton(«1/x»);

    JButton buttonSqrt = new JButton(«u221A»);

    ;

    Calculator() {

        prepareGUI();

        addComponents();

        addActionEvent();

    }

    public void prepareGUI() {

        frame = new JFrame();

        frame.setTitle(«Calculator»);

        frame.setSize(300, 490);

        frame.getContentPane().setLayout(null);

        frame.getContentPane().setBackground(Color.black);

        frame.setResizable(false);

        frame.setLocationRelativeTo(null);

        frame.setVisible(true);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

    public void addComponents() {

        label.setBounds(250, 0, 50, 50);

        label.setForeground(Color.white);

        frame.add(label);

        textField.setBounds(10, 40, 270, 40);

        textField.setFont(new Font(«Arial», Font.BOLD, 20));

        textField.setEditable(false);

        textField.setHorizontalAlignment(SwingConstants.RIGHT);

        frame.add(textField);

        onRadioButton.setBounds(10, 95, 60, 40);

        onRadioButton.setSelected(true);

        onRadioButton.setFont(new Font(«Arial», Font.BOLD, 14));

        onRadioButton.setBackground(Color.black);

        onRadioButton.setForeground(Color.white);

        frame.add(onRadioButton);

        offRadioButton.setBounds(10, 120, 60, 40);

        offRadioButton.setSelected(false);

        offRadioButton.setFont(new Font(«Arial», Font.BOLD, 14));

        offRadioButton.setBackground(Color.black);

        offRadioButton.setForeground(Color.white);

        frame.add(offRadioButton);

        ButtonGroup buttonGroup = new ButtonGroup();

        buttonGroup.add(onRadioButton);

        buttonGroup.add(offRadioButton);

        buttonSeven.setBounds(10, 230, 60, 40);

        buttonSeven.setFont(new Font(«Arial», Font.BOLD, 20));

        frame.add(buttonSeven);

        buttonEight.setBounds(80, 230, 60, 40);

        buttonEight.setFont(new Font(«Arial», Font.BOLD, 20));

        frame.add(buttonEight);

        buttonNine.setBounds(150, 230, 60, 40);

        buttonNine.setFont(new Font(«Arial», Font.BOLD, 20));

        frame.add(buttonNine);

        buttonFour.setBounds(10, 290, 60, 40);

        buttonFour.setFont(new Font(«Arial», Font.BOLD, 20));

        frame.add(buttonFour);

        buttonFive.setBounds(80, 290, 60, 40);

        buttonFive.setFont(new Font(«Arial», Font.BOLD, 20));

        frame.add(buttonFive);

        buttonSix.setBounds(150, 290, 60, 40);

        buttonSix.setFont(new Font(«Arial», Font.BOLD, 20));

        frame.add(buttonSix);

        buttonOne.setBounds(10, 350, 60, 40);

        buttonOne.setFont(new Font(«Arial», Font.BOLD, 20));

        frame.add(buttonOne);

        buttonTwo.setBounds(80, 350, 60, 40);

        buttonTwo.setFont(new Font(«Arial», Font.BOLD, 20));

        frame.add(buttonTwo);

        buttonThree.setBounds(150, 350, 60, 40);

        buttonThree.setFont(new Font(«Arial», Font.BOLD, 20));

        frame.add(buttonThree);

        buttonDot.setBounds(150, 410, 60, 40);

        buttonDot.setFont(new Font(«Arial», Font.BOLD, 20));

        frame.add(buttonDot);

        buttonZero.setBounds(10, 410, 130, 40);

        buttonZero.setFont(new Font(«Arial», Font.BOLD, 20));

        frame.add(buttonZero);

        buttonEqual.setBounds(220, 350, 60, 100);

        buttonEqual.setFont(new Font(«Arial», Font.BOLD, 20));

        buttonEqual.setBackground(new Color(239, 188, 2));

        frame.add(buttonEqual);

        buttonDiv.setBounds(220, 110, 60, 40);

        buttonDiv.setFont(new Font(«Arial», Font.BOLD, 20));

        buttonDiv.setBackground(new Color(239, 188, 2));

        frame.add(buttonDiv);

        buttonSqrt.setBounds(10, 170, 60, 40);

        buttonSqrt.setFont(new Font(«Arial», Font.BOLD, 18));

        frame.add(buttonSqrt);

        buttonMul.setBounds(220, 230, 60, 40);

        buttonMul.setFont(new Font(«Arial», Font.BOLD, 20));

        buttonMul.setBackground(new Color(239, 188, 2));

        frame.add(buttonMul);

        buttonMinus.setBounds(220, 170, 60, 40);

        buttonMinus.setFont(new Font(«Arial», Font.BOLD, 20));

        buttonMinus.setBackground(new Color(239, 188, 2));

        frame.add(buttonMinus);

        buttonPlus.setBounds(220, 290, 60, 40);

        buttonPlus.setFont(new Font(«Arial», Font.BOLD, 20));

        buttonPlus.setBackground(new Color(239, 188, 2));

        frame.add(buttonPlus);

        buttonSquare.setBounds(80, 170, 60, 40);

        buttonSquare.setFont(new Font(«Arial», Font.BOLD, 20));

        frame.add(buttonSquare);

        buttonReciprocal.setBounds(150, 170, 60, 40);

        buttonReciprocal.setFont(new Font(«Arial», Font.BOLD, 15));

        frame.add(buttonReciprocal);

        buttonDelete.setBounds(150, 110, 60, 40);

        buttonDelete.setFont(new Font(«Arial», Font.BOLD, 12));

        buttonDelete.setBackground(Color.red);

        buttonDelete.setForeground(Color.white);

        frame.add(buttonDelete);

        buttonClear.setBounds(80, 110, 60, 40);

        buttonClear.setFont(new Font(«Arial», Font.BOLD, 12));

        buttonClear.setBackground(Color.red);

        buttonClear.setForeground(Color.white);

        frame.add(buttonClear);

    }

    public void addActionEvent() {

        //Registering ActionListener to buttons

        onRadioButton.addActionListener(this);

        offRadioButton.addActionListener(this);

        buttonClear.addActionListener(this);

        buttonDelete.addActionListener(this);

        buttonDiv.addActionListener(this);

        buttonSqrt.addActionListener(this);

        buttonSquare.addActionListener(this);

        buttonReciprocal.addActionListener(this);

        buttonMinus.addActionListener(this);

        buttonSeven.addActionListener(this);

        buttonEight.addActionListener(this);

        buttonNine.addActionListener(this);

        buttonMul.addActionListener(this);

        buttonFour.addActionListener(this);

        buttonFive.addActionListener(this);

        buttonSix.addActionListener(this);

        buttonPlus.addActionListener(this);

        buttonOne.addActionListener(this);

        buttonTwo.addActionListener(this);

        buttonThree.addActionListener(this);

        buttonEqual.addActionListener(this);

        buttonZero.addActionListener(this);

        buttonDot.addActionListener(this);

    }

  //Overriding actionPerformed() method

    @Override

    public void actionPerformed(ActionEvent e) {

        Object source = e.getSource();

        if (source == onRadioButton) {

            enable();//Calling enable() function

        } else if (source == offRadioButton) {

            disable();//Calling disable function

        } else if (source == buttonClear) {

            //Clearing texts of label and text field

            label.setText(«»);

            textField.setText(«»);

        } else if (source == buttonDelete) {

            //Setting functionality for delete button(backspace)

            int length = textField.getText().length();

            int number = length 1;

            if (length > 0) {

                StringBuilder back = new StringBuilder(textField.getText());

                back.deleteCharAt(number);

                textField.setText(back.toString());

            }

            if (textField.getText().endsWith(«»)) {

                label.setText(«»);

            }

        } else if (source == buttonZero) {

            if (textField.getText().equals(«0»)) {

                return;

            } else {

                textField.setText(textField.getText() + «0»);

            }

        } else if (source == buttonOne) {

            textField.setText(textField.getText() + «1»);

        } else if (source == buttonTwo) {

            textField.setText(textField.getText() + «2»);

        } else if (source == buttonThree) {

            textField.setText(textField.getText() + «3»);

        } else if (source == buttonFour) {

            textField.setText(textField.getText() + «4»);

        } else if (source == buttonFive) {

            textField.setText(textField.getText() + «5»);

        } else if (source == buttonSix) {

            textField.setText(textField.getText() + «6»);

        } else if (source == buttonSeven) {

            textField.setText(textField.getText() + «7»);

        } else if (source == buttonEight) {

            textField.setText(textField.getText() + «8»);

        } else if (source == buttonNine) {

            textField.setText(textField.getText() + «9»);

        } else if (source == buttonDot) {

            if (textField.getText().contains(«.»)) {

                return;

            } else {

                textField.setText(textField.getText() + «.»);

            }

        } else if (source == buttonPlus) {

            String str = textField.getText();

            number = Double.parseDouble(textField.getText());

            textField.setText(«»);

            label.setText(str + «+»);

            calculation = 1;

        } else if (source == buttonMinus) {

            String str = textField.getText();

            number = Double.parseDouble(textField.getText());

            textField.setText(«»);

            label.setText(str + «-«);

            calculation = 2;

        } else if (source == buttonMul) {

            String str = textField.getText();

            number = Double.parseDouble(textField.getText());

            textField.setText(«»);

            label.setText(str + «X»);

            calculation = 3;

        } else if (source == buttonDiv) {

            String str = textField.getText();

            number = Double.parseDouble(textField.getText());

            textField.setText(«»);

            label.setText(str + «/»);

            calculation = 4;

        } else if (source == buttonSqrt) {

            number = Double.parseDouble(textField.getText());

            Double sqrt = Math.sqrt(number);

            textField.setText(Double.toString(sqrt));

        } else if (source == buttonSquare) {

            String str = textField.getText();

            number = Double.parseDouble(textField.getText());

            double square = Math.pow(number, 2);

            String string = Double.toString(square);

            if (string.endsWith(«.0»)) {

                textField.setText(string.replace(«.0», «»));

            } else {

                textField.setText(string);

            }

            label.setText(«(sqr)» + str);

        } else if (source == buttonReciprocal) {

            number = Double.parseDouble(textField.getText());

            double reciprocal = 1 / number;

            String string = Double.toString(reciprocal);

            if (string.endsWith(«.0»)) {

                textField.setText(string.replace(«.0», «»));

            } else {

                textField.setText(string);

            }

        } else if (source == buttonEqual) {

           //Setting functionality for equal(=) button

            switch (calculation) {

                case 1:

                    answer = number + Double.parseDouble(textField.getText());

                    if (Double.toString(answer).endsWith(«.0»)) {

                        textField.setText(Double.toString(answer).replace(«.0», «»));

                    } else {

                        textField.setText(Double.toString(answer));

                    }

                    label.setText(«»);

                    break;

                case 2:

                    answer = number Double.parseDouble(textField.getText());

                    if (Double.toString(answer).endsWith(«.0»)) {

                        textField.setText(Double.toString(answer).replace(«.0», «»));

                    } else {

                        textField.setText(Double.toString(answer));

                    }

                    label.setText(«»);

                    break;

                case 3:

                    answer = number * Double.parseDouble(textField.getText());

                    if (Double.toString(answer).endsWith(«.0»)) {

                        textField.setText(Double.toString(answer).replace(«.0», «»));

                    } else {

                        textField.setText(Double.toString(answer));

                    }

                    label.setText(«»);

                    break;

                case 4:

                    answer = number / Double.parseDouble(textField.getText());

                    if (Double.toString(answer).endsWith(«.0»)) {

                        textField.setText(Double.toString(answer).replace(«.0», «»));

                    } else {

                        textField.setText(Double.toString(answer));

                    }

                    label.setText(«»);

                    break;

            }

        }

    }

    public void enable() {

        onRadioButton.setEnabled(false);

        offRadioButton.setEnabled(true);

        textField.setEnabled(true);

        label.setEnabled(true);

        buttonClear.setEnabled(true);

        buttonDelete.setEnabled(true);

        buttonDiv.setEnabled(true);

        buttonSqrt.setEnabled(true);

        buttonSquare.setEnabled(true);

        buttonReciprocal.setEnabled(true);

        buttonMinus.setEnabled(true);

        buttonSeven.setEnabled(true);

        buttonEight.setEnabled(true);

        buttonNine.setEnabled(true);

        buttonMul.setEnabled(true);

        buttonFour.setEnabled(true);

        buttonFive.setEnabled(true);

        buttonSix.setEnabled(true);

        buttonPlus.setEnabled(true);

        buttonOne.setEnabled(true);

        buttonTwo.setEnabled(true);

        buttonThree.setEnabled(true);

        buttonEqual.setEnabled(true);

        buttonZero.setEnabled(true);

        buttonDot.setEnabled(true);

    }

    public void disable() {

        onRadioButton.setEnabled(true);

        offRadioButton.setEnabled(false);

        textField.setText(«»);

        label.setText(» «);

        buttonClear.setEnabled(false);

        buttonDelete.setEnabled(false);

        buttonDiv.setEnabled(false);

        buttonSqrt.setEnabled(false);

        buttonSquare.setEnabled(false);

        buttonReciprocal.setEnabled(false);

        buttonMinus.setEnabled(false);

        buttonSeven.setEnabled(false);

        buttonEight.setEnabled(false);

        buttonNine.setEnabled(false);

        buttonMul.setEnabled(false);

        buttonFour.setEnabled(false);

        buttonFive.setEnabled(false);

        buttonSix.setEnabled(false);

        buttonPlus.setEnabled(false);

        buttonOne.setEnabled(false);

        buttonTwo.setEnabled(false);

        buttonThree.setEnabled(false);

        buttonEqual.setEnabled(false);

        buttonZero.setEnabled(false);

        buttonDot.setEnabled(false);

    }

}

Базовый калькулятор на Java может сложить, вычесть, умножить или разделить два числа. Это делается с помощью переключателя. Программа, которая демонстрирует это –

Пример

import java.util.Scanner;
public class Calculator {
   public static void main(String[] args) {
      double num1;
      double num2;
      double ans;
      char op;
      Scanner reader = new Scanner(System.in);
      System.out.print("Enter two numbers: ");
      num1 = reader.nextDouble();
      num2 = reader.nextDouble();
      System.out.print("nEnter an operator (+, -, *, /): ");
      op = reader.next().charAt(0);
      switch(op) {
         case '+': ans = num1 + num2;
            break;
         case '-': ans = num1 - num2;
            break;
         case '*': ans = num1 * num2;
            break;
         case '/': ans = num1 / num2;
            break;
         default:  System.out.printf("Error! Enter correct operator");
            return;
      }
      System.out.print("nThe result is given as follows:n");
      System.out.printf(num1 + " " + op + " " + num2 + " = " + ans);
   }
}

Вывод

Enter two numbers: 10.0 7.0
Enter an operator (+, -, *, /): -
The result is given as follows:
10.0 - 7.0 = 3.0

Два числа, а также оператор задаются от пользователя. Фрагмент кода, демонстрирующий это, приведен ниже:

double num1;
double num2;
double ans;
char op;
Scanner reader = new Scanner(System.in);
System.out.print("Enter two numbers: ");
num1 = reader.nextDouble();
num2 = reader.nextDouble();
System.out.print("nEnter an operator (+, -, *, /): ");
op = reader.next().charAt(0);

Переключатель используется для выполнения указанной операции над двумя числами. Если введенный оператор неверен, отображается сообщение об ошибке.

switch(op) {
   case '+': ans = num1 + num2;
      break;
   case '-': ans = num1 - num2;
      break;
   case '*': ans = num1 * num2;
      break;
   case '/': ans = num1 / num2;
      break;
   default:  System.out.printf("Error! Enter correct operator");
      return;
}

Наконец, выводится результат.

System.out.print("nThe result is given as follows:n");
System.out.printf(num1 + " " + op + " " + num2 + " = " + ans);

Introduction: Creating a Basic Calculator in Java

Computers are becoming more and more prevalent in our world as time moves forward. It is becoming more and more important for someone to have at least some knowledge in code. A calculator coded in java should be an easy introduction.

There is no need for previous knowledge in coding for someone to complete these instructions. All that is needed is a working computer (Windows or Mac). As well as java installed as well as Eclipse, both of which will be covered in the instructions.

Supplies

https://java.com/en/

https://www.eclipse.org/downloads/

Step 1: Installing Java

In order to begin, java must be installed onto your computer. Begin by visiting their website. Click on Java Download (See Figure 1) to be directed to the download page. The website will automatically detect your operating system which will allow you to install the correct version.

Once you have reached the download page, click on Agree and Start Free Download

Once the installer is downloaded, run the program and once you reach the first page, click Install at the bottom. Once clicked, you should see java installing onto your computer (Figure 2)

Once it states you have successfully installed java, click close.

Step 2: Installing Eclipse

In order to actually write the code for the calculator, you will need the software in order to do it. For this we will be using a program called Eclipse. This is the same program that students at ISU use for programming projects in java.

To install Eclipse, first go to the homepage HERE. Once there, click the orange download button. (See figure 3)

Eclipse download Once downloaded, run the program. When presented with a list of selections, choose Eclipse IDE for Java Developers. (See figure 4)

Then, select the destination for eclipse to be installed in if the default location does not work for you. Then, click install. (Figure 5) Once installed, click the green launch button. (See Figure 6)

Finally, once Eclipse is launched, select the destination you wish your work to be saved if the default location does not work for you. Once selected, click launch.(See Figure 7)

Step 3: Creating a Project

Now that eclipse is installed, we can now create a project to put our code into. To begin, click File — New — Java Project. (See Figure 8)

Name your project whatever you seem fit, in our case Calculator works. Once you named your project, click Finish in the bottom right. (See Figure 9)

Step 4: Creating a Class

Once your project is created, right click the project folder at the top left, then click New — Class. (See Figure 10)

A class is a user defined blueprint for the code to be written in. In this class we can write what is called a method. A method is a collection of statements or code that are grouped together to perform an operation.

Choose a name for the class, in this case I will be naming it Calculator. However any name works. Make sure that the box public static void main(String[ ] args) is checked. This will allow us to display the output for the calculator. (See figure 11)

Step 5: Creating Our Variables

Before we define our variables, let’s go over what we are looking at when we create our class. Each class is enclosed using brackets, anything written within those brackets will be a part of the class. The same goes for methods. All of our code will be written in the public static void main(String[ ] args) method, or the main method. (See figure 12)

First, we will define two variables. Variables can be a number of data types. Integers (1, 2, 3…), Doubles (1.2, 0.00004, 19.5…) or Strings (“Hello”, “Hi”, “Letters”) just to name the basics. In our case we will define 2 integers, defined using the phrase int. In our case we name them firstNum and secondNum and set them equal to 0. (See figure 13)

Step 6: Creating a Scanner

A scanner allows the user of the program to input something using the keyboard. In our case they will use the scanner to input the numbers and select the operation.

To create a scanner first you must import java.util. This can be done by typing import java.util.*; above the class. Next inside of the main method you must create a scanner object, this can be done by typing in Scanner scan = new Scanner(System.in); (See figure 14)

What this means is that you have created a new scanner object under the variable name scan. This is the name you will use to access the scanner later in the class.

Step 7: Setting Variables to User Input

For this step. We will be allowing the variables we created to be set to whatever the user inputs into the program, so long as the inputs are integers.

First, you must display a message to the user instructing them to input an integer. This can be done by typing System.out.println(); Within the parentheses, type in quotes “Please input first integer:”

After that line is complete. You must set the typed integer as firstNum. This can be done by typing firstNum = scan.nextInt();

Now do this process again, this time assigning the input as secondNum.(See figure 15)

Step 8: Creating Operations

It isn’t a calculator if there are no operations it can perform. To start, you must create two more variables, an integer call operator. As well as a double called answer, which is set to 0.

Afterwards, create an output like before, this time asking the user which operation they would like to perform. The user will then choose an operator by typing in a number 1-4, each representing a different operation. After this, set the user’s input to the operator integer. (See figure 16)

Step 9: Switch Operation

Finally, we must set the operator variable to a certain calculator operation. This can be done by using what is called a Switch Statement. What this does is takes a certain set of cases and chooses one to run. In our case integers 1 through 4 were assigned to different operations. Depending on the number input by the user, the program will perform the desired operation.

First write out switch(operator) along with a set of brackets. Within these brackets are where the different cases will be written. Each case will be defined by the integer that has been input. Follow the code written below in Figure 17 for each specific operation.

Finally, write out one final output which will display the answer to the operation. This can be done by typing out the code listed at the bottom of figure 17.

Step 10: Testing the Program

Finally, run the program by clicking Run — Run at the top of Eclipse. The calculator is used in the console of eclipse and requires inputs from the user. Input 5 as the first integer and 4 as the second integer. Then select the multiply operation by typing in 3 when the prompt comes up. Your output should look like this: (See figure 18)

And with that you have completed a calculator program in Java. Hopefully this has taught you at least a small amount of Java coding information.

To see the final code, see figure 19.

Be the First to Share

Recommendations

Introduction: Creating a Basic Calculator in Java

Computers are becoming more and more prevalent in our world as time moves forward. It is becoming more and more important for someone to have at least some knowledge in code. A calculator coded in java should be an easy introduction.

There is no need for previous knowledge in coding for someone to complete these instructions. All that is needed is a working computer (Windows or Mac). As well as java installed as well as Eclipse, both of which will be covered in the instructions.

Supplies

https://java.com/en/

https://www.eclipse.org/downloads/

Step 1: Installing Java

In order to begin, java must be installed onto your computer. Begin by visiting their website. Click on Java Download (See Figure 1) to be directed to the download page. The website will automatically detect your operating system which will allow you to install the correct version.

Once you have reached the download page, click on Agree and Start Free Download

Once the installer is downloaded, run the program and once you reach the first page, click Install at the bottom. Once clicked, you should see java installing onto your computer (Figure 2)

Once it states you have successfully installed java, click close.

Step 2: Installing Eclipse

In order to actually write the code for the calculator, you will need the software in order to do it. For this we will be using a program called Eclipse. This is the same program that students at ISU use for programming projects in java.

To install Eclipse, first go to the homepage HERE. Once there, click the orange download button. (See figure 3)

Eclipse download Once downloaded, run the program. When presented with a list of selections, choose Eclipse IDE for Java Developers. (See figure 4)

Then, select the destination for eclipse to be installed in if the default location does not work for you. Then, click install. (Figure 5) Once installed, click the green launch button. (See Figure 6)

Finally, once Eclipse is launched, select the destination you wish your work to be saved if the default location does not work for you. Once selected, click launch.(See Figure 7)

Step 3: Creating a Project

Now that eclipse is installed, we can now create a project to put our code into. To begin, click File — New — Java Project. (See Figure 8)

Name your project whatever you seem fit, in our case Calculator works. Once you named your project, click Finish in the bottom right. (See Figure 9)

Step 4: Creating a Class

Once your project is created, right click the project folder at the top left, then click New — Class. (See Figure 10)

A class is a user defined blueprint for the code to be written in. In this class we can write what is called a method. A method is a collection of statements or code that are grouped together to perform an operation.

Choose a name for the class, in this case I will be naming it Calculator. However any name works. Make sure that the box public static void main(String[ ] args) is checked. This will allow us to display the output for the calculator. (See figure 11)

Step 5: Creating Our Variables

Before we define our variables, let’s go over what we are looking at when we create our class. Each class is enclosed using brackets, anything written within those brackets will be a part of the class. The same goes for methods. All of our code will be written in the public static void main(String[ ] args) method, or the main method. (See figure 12)

First, we will define two variables. Variables can be a number of data types. Integers (1, 2, 3…), Doubles (1.2, 0.00004, 19.5…) or Strings (“Hello”, “Hi”, “Letters”) just to name the basics. In our case we will define 2 integers, defined using the phrase int. In our case we name them firstNum and secondNum and set them equal to 0. (See figure 13)

Step 6: Creating a Scanner

A scanner allows the user of the program to input something using the keyboard. In our case they will use the scanner to input the numbers and select the operation.

To create a scanner first you must import java.util. This can be done by typing import java.util.*; above the class. Next inside of the main method you must create a scanner object, this can be done by typing in Scanner scan = new Scanner(System.in); (See figure 14)

What this means is that you have created a new scanner object under the variable name scan. This is the name you will use to access the scanner later in the class.

Step 7: Setting Variables to User Input

For this step. We will be allowing the variables we created to be set to whatever the user inputs into the program, so long as the inputs are integers.

First, you must display a message to the user instructing them to input an integer. This can be done by typing System.out.println(); Within the parentheses, type in quotes “Please input first integer:”

After that line is complete. You must set the typed integer as firstNum. This can be done by typing firstNum = scan.nextInt();

Now do this process again, this time assigning the input as secondNum.(See figure 15)

Step 8: Creating Operations

It isn’t a calculator if there are no operations it can perform. To start, you must create two more variables, an integer call operator. As well as a double called answer, which is set to 0.

Afterwards, create an output like before, this time asking the user which operation they would like to perform. The user will then choose an operator by typing in a number 1-4, each representing a different operation. After this, set the user’s input to the operator integer. (See figure 16)

Step 9: Switch Operation

Finally, we must set the operator variable to a certain calculator operation. This can be done by using what is called a Switch Statement. What this does is takes a certain set of cases and chooses one to run. In our case integers 1 through 4 were assigned to different operations. Depending on the number input by the user, the program will perform the desired operation.

First write out switch(operator) along with a set of brackets. Within these brackets are where the different cases will be written. Each case will be defined by the integer that has been input. Follow the code written below in Figure 17 for each specific operation.

Finally, write out one final output which will display the answer to the operation. This can be done by typing out the code listed at the bottom of figure 17.

Step 10: Testing the Program

Finally, run the program by clicking Run — Run at the top of Eclipse. The calculator is used in the console of eclipse and requires inputs from the user. Input 5 as the first integer and 4 as the second integer. Then select the multiply operation by typing in 3 when the prompt comes up. Your output should look like this: (See figure 18)

And with that you have completed a calculator program in Java. Hopefully this has taught you at least a small amount of Java coding information.

To see the final code, see figure 19.

Be the First to Share

Recommendations

Понравилась статья? Поделить с друзьями:
  • Как написать программу записная книжка
  • Как написать программу дополнительного образования для навигатора
  • Как написать программу для чпу станка фрезеровка
  • Как написать программу для управления устройством
  • Как написать программу диалог