最近,我研究了可以加,减,乘和除的简单计算器。
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); } } }
但是,如果我想让程序像普通计算器一样工作,该怎么办?它加,减,乘,除,…,但不仅是两个,而是多个。
当然可以做到!尽管需要实质性的框架。但是,如果要使用这种简单的代码,则需要将数字存储在此函数之外的其他位置,并且将要对其进行操作的每两个数字进行存储,并将其用作第一个参数您要使用的第三个。等等。这有意义吗?