java编写一个简单计算器(实现加减乘除)
程序员文章站
2022-07-10 18:47:25
初学java,试着写了一个小程序,可能有很多不足,希望大家多多见谅。import java.util.Scanner;public class Demo04 { public static void main(String[] args) { while (true) { Scanner scanner = new Scanner(System.in); System.out.println("请输入要操作的选项:1 加法 2 减法...
初学java,试着写了一个小程序,可能有很多不足,希望大家多多见谅。
import java.util.Scanner; public class Demo04 { public static void main(String[] args) { while (true) { Scanner scanner = new Scanner(System.in); System.out.println("请输入要操作的选项:1 加法 2 减法 3 乘法 4 除法"); String s = scanner.next(); char select = s.charAt(0); switch (select) { case '1': System.out.println("请输入第一个数:"); double a = scanner.nextDouble(); System.out.println("请输入第二个数:"); double b = scanner.nextDouble(); double sum = add(a, b); System.out.println("两个数的和为:" + sum); break; case '2': System.out.println("请输入被减数:"); double c = scanner.nextDouble(); System.out.println("请输入减数:"); double d = scanner.nextDouble(); double difference = reduce(c, d); System.out.println("两个数的差为:" + difference); break; case '3': System.out.println("请输入第一个数:"); double e = scanner.nextDouble(); System.out.println("请输入第二个数:"); double f = scanner.nextDouble(); double ride = ride(e, f); System.out.println("两个数的积为:" + ride); break; case '4': System.out.println("请输入被除数:"); double g = scanner.nextDouble(); System.out.println("请输入除数:"); double h = scanner.nextDouble(); double except = except(g, h); System.out.println("两个数的商为:" + except); default: System.out.println("你的输入有误,请重新输入:"); continue; } System.out.println("是否继续?是请输入Y,输入其他退出"); String input = scanner.next(); char go = input.charAt(0); if (go != 'Y'){ break; } } } public static double add(double a,double b){ return a + b; } public static double reduce(double a,double b){ return a - b; } public static double ride(double a,double b){ return a * b; } public static double except(double a,double b){ return a / b; } }
运行结果:
本文地址:https://blog.csdn.net/qq479850581/article/details/107895440