java中的计算器 [英] Calculator in java

查看:111
本文介绍了java中的计算器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我一直致力于简单的计算器,可以添加,减去,乘法和除法。

Lately I've worked on simple calculator that can add, substract, multiply and divide.

public static void main(String arr[]){ 
    double num1, num2;
    String ans = null;

    System.out.println("Calculator manu:");
    System.out.println("\n"+"a for adding"); 
    System.out.println("b for substracting");
    System.out.println("c for multiplying");
    System.out.println("d for dividing");

    Scanner NumInput = new Scanner(System.in);

    System.out.println("\n"+"Enter number one: ");
    num1 = NumInput.nextDouble();

    System.out.println("\n"+"Enter number two: ");
    num2 = NumInput.nextDouble();

    while(true)
    {   
    Scanner AnsInput = new Scanner(System.in);
    System.out.println("\n"+"Choose operation.");
    String answer = AnsInput.next();


    if(AnsInput.equals("1"))
    {
        answer = Double.toString(num1+num2);
        System.out.println("\n"+"The sum of the first and second number is: "+answer);
    }
    else if(AnsInput.equals("2")) 
    {
        answer = Double.toString(num1-num2);
        System.out.println("\n"+"Subtraction of the first and the second number is: "+answer);
    }
    else if(AnsInput.equals("3"))
    {
        answer = Double.toString(num1*num2);
        System.out.println("\n"+"The product of the first and second number is: "+answer);
    }
    else if(AnsInput.equals("4"))
    {
        answer = Double.toString(num1/num2);
        System.out.println("\n"+"Ratio of the first and the second number is: "+answer);
    }
    }
}

但如果我想要怎么办?像普通计算器一样工作的赖特程序;它增加,减去,乘以,除,......,但不仅仅是两个而是多个数字。

But what if I want to wright program that works like an ordinary calculator; it adds, subtracts, multiplies, divides, ... ,but not only whit two but multiple numbers.

推荐答案

这当然可以完成!虽然它需要实质性的框架。但是,如果你想使用这种类型的简单代码,你需要做的是将数字存储在其他地方,在这个函数之外,以及你应用操作的每两个数字,你存储它并将它用作第一个参数你想要使用的第三个。等等。这有意义吗?

This can certainly be done! Although it requires substantial framework. However, if you want to use this type of simplistic code, what you need to do is store the numbers somewhere else, outside this function, and every two numbers you apply an operation to, you store it and use it as the first argument along the third you wanted to use. And so on. Does this make sense?

这篇关于java中的计算器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆