Java写一个简单的计算器,能计算加减乘除,接收用户输入并能够循环接收数据
Posted 禾千
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java写一个简单的计算器,能计算加减乘除,接收用户输入并能够循环接收数据相关的知识,希望对你有一定的参考价值。
package com.lyn.Methon;
import java.util.Scanner;
public class CalDemo {
//写一个计算器,要求能计算加减乘除,并能够循环接收数据,且接收用户输入
//写4个方法,加减乘除
//利用循环+switch进行用户交互
//传递需要操作的两个数,并输出结果
public static void main(String[] args) {
while(true){
System.out.println("请输入计算类型(+,-,*,/) ,或使用quit退出 ");
Scanner scanner = new Scanner(System.in);
String cal = scanner.nextLine();
if (cal.equals("quit")){
System.out.println("已退出计算器");
break;
}else {
System.out.println("输入要进行计算的两个数,回车分割:");
switch (cal) {
case "+":
Scanner num1 = new Scanner(System.in);
double addNum1 = num1.nextDouble();
Scanner num2 = new Scanner(System.in);
double addNum2 = num2.nextDouble();
double add = add(addNum1,addNum2);
System.out.println(addNum1 + "+" + addNum2 + "=" + add);
break;
case "-":
Scanner num3 = new Scanner(System.in);
double minusNum1 = num3.nextDouble();
Scanner num4 = new Scanner(System.in);
double minusNum2 = num4.nextDouble();
double minus = minus(minusNum1,minusNum2);
System.out.println(minusNum1+"-"+minusNum2+"="+minus);
break;
case "*":
Scanner num5 = new Scanner(System.in);
double multiplyNum1 = num5.nextDouble();
Scanner num6 = new Scanner(System.in);
double multiplyNum2 = num6.nextDouble();
double multiply = multiply(multiplyNum1,multiplyNum2);
System.out.println(multiplyNum1+"*"+multiplyNum2+"="+multiply);
break;
case "/":
Scanner num7 = new Scanner(System.in);
double divideNum1 = num7.nextDouble();
Scanner num8 = new Scanner(System.in);
double divideNum2 = num8.nextDouble();
double divide = divide(divideNum1,divideNum2);
System.out.println(divideNum1+"/"+divideNum2+"="+divide);
break;
}
}
}
}
public static double add(double x, double y){
return x+y;
}
public static double minus(double x, double y){
return x-y;
}
public static double multiply(double x, double y){
return x*y;
}
public static double divide(double x,double y){
return x/y;
}
}
以上是关于Java写一个简单的计算器,能计算加减乘除,接收用户输入并能够循环接收数据的主要内容,如果未能解决你的问题,请参考以下文章
使用javafx技术编写一个计算器的程序,在计算器的界面上能进行加减乘除的操作