How to use JAVA to write a simple calculator

How to use JAVA to write a simple calculator

If you find it useful, please like or follow~ More useful content will be released in the future.


Xiaobai: How does JAVA write a calculator? ? ? With a dumb look...

Teacher: Let you not listen carefully


Teaching time

Idea: Use the nature of the if statement to determine the input operator.
Judge which calculation statement to execute, and then calculate and output the result.

Knowledge points:
if ···judgment statement
else ···otherwise statement
double···floating point function
char···character function


Below is the implemented code

import java.util.Scanner;

public class 计算器{
    
    

	public static void main(String[] args) {
    
    
	        System.out.println("这是一个可以计算 +, -, *, /, 的计算器"); 
			Scanner num=new Scanner(System.in);  
			System.out.println("请输入第一个计算的数字");    
		double num1=num.nextInt(); 
			System.out.println("请输入一个运算符"); 
		char x = num.next().charAt(0);  
			System.out.println("请输入第二个计算的数字");   
		double num2=num.nextInt(); 
			
		double result ;
		if (x=='+') {
    
     
			result=num1+num2;
			System.out.println(num1+"+"+num2+"="+result);
		}
		else if (x=='-') {
    
    
		    result=num1-num2;
			System.out.println(num1+"-"+num2+"="+result);
		}
		else if (x=='*') {
    
    
		    result=num1*num2;
			System.out.println(num1+"*"+num2+"="+result);
		}
		else if (x=='/') {
    
    
			result=num1/num2;
			System.out.println(num1+"/"+num2+"="+result);
		}
		else 
		    System.out.println("我就知道有憨憨会输入错误0.0");

	}

}

Guess you like

Origin blog.csdn.net/cpm011023/article/details/114372518