Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

I build a calculator in unity, but it can't calculate 2 digit numbers

Discussion in '2D' started by Netherknight666, Jan 18, 2020.

  1. Netherknight666

    Netherknight666

    Joined:
    Jun 18, 2019
    Posts:
    4
    I trying to create calculator here, however it can only calculate 1 digit number. When I try 2 digits number it's calculate wrong. For example, I tried 11+1 but the answer is 2.

    here the code:
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.UI;
    using UnityEngine.EventSystems;

    public class Calculator : MonoBehaviour
    {
    [SerializeField]
    Text inputField;

    string inputString;
    int[] number = new int[2];
    string operatorSymbol;
    int i = 0;
    int result;
    bool displayerResults = false;
    public void ButtonPressed()
    {
    if(displayerResults == true)
    {
    inputField.text = "";
    inputString = "";
    displayerResults = false;
    }
    string buttonValue = EventSystem.current.currentSelectedGameObject.name;
    inputString += buttonValue;

    int arg;
    if (int.TryParse(buttonValue, out arg))
    {
    if (i > 1) i = 0;
    number = arg;
    i = i + 1;
    }
    else
    {
    switch (buttonValue)
    {
    case "+":
    operatorSymbol = buttonValue;
    break;
    case "-":
    operatorSymbol = buttonValue;
    break;
    case "x":
    operatorSymbol = buttonValue;
    break;
    case "÷":
    operatorSymbol = buttonValue;
    break;
    case "=":
    switch (operatorSymbol)
    {
    case "+":
    result = number[0] + number[1];
    break;
    case "-":
    result = number[0] - number[1];
    break;
    case "x":
    result = number[0] * number[1];
    break;
    case "÷":
    result = number[0] / number[1];
    break;
    }
    displayerResults = true;
    inputString = result.ToString();
    number = new int[2];
    break;
    }
    }
    inputField.text = inputString;
    }
    }
    upload_2020-1-18_15-45-20.png
     
  2. Agent003

    Agent003

    Joined:
    Sep 7, 2018
    Posts:
    55
  3. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,594