Java public class calculator

Simple Java calculator

Firstly this is not a homework question. I am practicing my knowledge on java. I figured a good way to do this is to write a simple program without help. Unfortunately, my compiler is telling me errors I don’t know how to fix. Without changing much logic and code, could someone kindly point out where some of my errors are? Thanks

import java.lang.*; import java.util.*; public class Calculator < private int solution; private int x; private int y; private char operators; public Calculator() < solution = 0; Scanner operators = new Scanner(System.in); Scanner operands = new Scanner(System.in); >public int addition(int x, int y) < return x + y; >public int subtraction(int x, int y) < return x - y; >public int multiplication(int x, int y) < return x * y; >public int division(int x, int y) < solution = x / y; return solution; >public void main (String[] args) < System.out.println("What operation? ('+', '-', '*', '/')"); System.out.println("Insert 2 numbers to be subtracted"); System.out.println("operand 1: "); x = operands; System.out.println("operand 2: "); y = operands.next(); switch(operators) < case('+'): addition(operands); operands.next(); break; case('-'): subtraction(operands); operands.next(); break; case('*'): multiplication(operands); operands.next(); break; case('/'): division(operands); operands.next(); break; >> > 

Thanks for posting your code. However, it also helps a lot when you post the text of the error messages you’re getting from the compiler — this makes it easier for people to quickly identify the problem (without having to read the whole code or compile it themselves).

Читайте также:  Оптимизация функций в питоне

Источник

LatTony / Calculator.java

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

// ****
// calc
// ****
import java . util . Scanner ; // Подключаем дерективу для ввода с клавиатуры
public class Calculator
public static void main ( String [] args )
Scanner input = new Scanner ( System . in );
Main result = new Main ();
System . out . println ( «Input:» ); // Запрос ввода
String expression = input . nextLine (); // Ввод выражения
String answer = result . calc ( expression ); // Метод calc для объекта result
System . out . println ( «Output: \n » + answer ); // Выводим ответ
>
>
class Main
public static String calc ( String input )
boolean romanOrArab = false ; // Для понимания какое число на выходе (рим или араб)
String exception = «throws Exception» ; // Исключение
Main romanExamination = new Main (); // Вводим для проверки и перевода из рим в араб
Main arabToRoman = new Main (); // Для перевода ответа в римские
int result = 0 ; // Считает выражение
String [] inputSplit = input . split ( » » );
if ( inputSplit . length != 3 )
return exception ; // Ловим, если не 3 элемента
>
Integer firstNumber = 0 ;
Integer secondNumber = 0 ;
try
firstNumber = Integer . valueOf ( inputSplit [ 0 ]);
secondNumber = Integer . valueOf ( inputSplit [ 2 ]);
> catch ( NumberFormatException e ) < // Ловим, если не арабское
try
firstNumber = romanExamination . romanToArab ( inputSplit [ 0 ]);
secondNumber = romanExamination . romanToArab ( inputSplit [ 2 ]);
romanOrArab = true ;
> catch ( NumberFormatException ex ) < // Ловим, если не римское
return exception ;
>
>
if (( firstNumber < 1 ) || ( firstNumber >10 ) || ( secondNumber < 1 ) || ( secondNumber >10 ))
return exception ; // Указываем диапазон значений
>
String sign = inputSplit [ 1 ];
switch ( sign )
case «+» -> result = firstNumber + secondNumber ;
case «-» -> result = firstNumber — secondNumber ;
case «*» -> result = firstNumber * secondNumber ;
case «/» -> result = firstNumber / secondNumber ;
default ->
return exception ; // Ловим, если не знак
>
>
String output ; // Наш вывод
if ( romanOrArab )
if ( result < 1 )
return exception ;
> else
output = arabToRoman . arabToRome ( result );
>
> else
output = Integer . toString ( result );
>
return output ;
>
Integer romanToArab ( String romanInput ) < // Переводим римский ввод в арабский
int result = 0 ;
int [] arab = < 10 , 9 , 5 , 4 , 1 >;
String [] roman = < "X" , "IX" , "V" , "IV" , "I" >;
for ( int i = 0 ; i < arab . length ; i ++ )
while ( romanInput . indexOf ( roman [ i ]) == 0 )
result += arab [ i ];
romanInput = romanInput . substring ( roman [ i ]. length ()); // Исключаем посчитанные числа
>
>
return result ;
>
String arabToRome ( int arabInput ) < // Перевод араб в рим
String result = «» ;
int value = 0 ;
int [] arab = < 100 , 90 , 50 , 40 , 10 , 9 , 5 , 4 , 1 >;
String [] roman = < "C" , "XC" , "L" , "XL" , "X" , "IX" , "V" , "IV" , "I" >;
for ( int i = 0 ; i < arab . length ; i ++)
value = arabInput / arab [ i ];
for ( int j = 0 ; j < value ; j ++)
result = result . concat ( roman [ i ]);
>
arabInput = arabInput % arab [ i ];
>
return result ;
>
>

Источник

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.

aepikalov/JavaPatterns_2_1_Structural

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

В этом задании попрактикуемся с шаблоном Adapter (Адаптер). Ниже вам дан готовый класс калькулятора:

public class Calculator < public Formula newFormula() < return new Formula(); > public static enum Operation < SUM, SUB, MULT, DIV, POW; > public static class Formula < protected Double a, b, result; protected Formula() <> public Formula addOperand(double operand) < if (a == null) < a = operand; > else if (b == null) < b = operand; > else < throw new IllegalStateException("Formula is full of operands"); > return this; > public Formula calculate(Operation op) < if (a == null || b == null) throw new IllegalStateException("Not enough operands!"); switch (op) < case SUM: result = a + b; break; case SUB: result = a - b; break; case MULT: result = a * b; break; case DIV: result = a / b; break; case POW: result = Math.pow(a, b); break; > return this; > public double result() < if (result == null) throw new IllegalStateException("Formula is not computed!"); return result; > > >

Пример использования этого класса:

Calculator calc = new Calculator(); System.out.println( calc.newFormula() .addOperand(5) .addOperand(15) .calculate(Calculator.Operation.MULT) .result() );

Пользователю же нужен другой интерфейс для работы с калькулятором:

public interface Ints < int sum(int arg0, int arg1); int mult(int arg0, int arg1); int pow(int a, int b); >

который он использует в main , например, вот так:

public static void main(String[] args) < Ints intsCalc = new IntsCalculator(); System.out.println(intsCalc.sum(2, 2)); System.out.println(intsCalc.sum(10, 22)); System.out.println(intsCalc.pow(2, 10)); >

Вам надо написать класс IntsCalculator , который будет имплементировать интерфейс Ints , «под капотом» делая вычисления через класс Calculator .

  1. Создайте класс Calculator , скопируйте его готовый код выше.
  2. Создайте интерфейс Ints , скопируйте его готовый код выше.
  3. Создайте класс IntsCalculator , укажите что он имплементирует интерфейс Ints , реализуйте его методы через обращение к объекту класса Calculator :
public class IntsCalculator implements Ints < protected final Calculator target; public IntsCalculator() < this.target = new Calculator(); > @Override public int sum(int arg0, int arg1) < //считаем через target > @Override public int mult(int arg0, int arg1) < //считаем через target > @Override public int pow(int a, int b) < //считаем через target > >
  1. Создайте класс Main , продемонстрируйте использование и возможности вашего класса (например, как выше в условии), обращайтесь к нему как к объекту интерфейса Ints .
public class Main < public static void main(String[] args) < Ints calc = new IntsCalculator(); //демонстрация > >
  1. Протестируйте работу программы. Не забывайте про правила форматирования кода (для автоформата можете выделить код в идее и нажать Ctrl+Alt+L).

Источник

Basic calculator in Java

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)); >> > 

10 Answers 10

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

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

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; >> 

While this code technically works, it does so by operating significantly differently from the code in the question, in a way that avoids addressing any of the bugs in that code.

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( "*"))

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

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)); >> 

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) Addition\n"); System.out.print("(2) Subtraction\n"); System.out.print("(3) Multiplication\n"); System.out.print("(4) Division\n"); System.out.print("(5) Exit\n\n"); 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); > > 

maybe its better using the case instead of if dunno if this eliminates the error, but its cleaner i think.. switch (operation)

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"); >> 
public class SwitchExample < public static void main(String[] args) throws Exception < System.out.println(". Start. "); System.out.println("\n\n"); 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); >

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)); >> 
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)); >> > 

Источник

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