Java教程

【狂神说Java】练习

本文主要是介绍【狂神说Java】练习,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
/*
计算器,基本加减乘除。
*/
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        //主程序
        Scanner scanner = new Scanner(System.in);
        boolean flag = true;
        while (flag) {
            System.out.println("请输入\"加\"、\"减\"、\"乘\"、\"除\"进行运算");
            String str = scanner.nextLine();
            String[] str1;
            String str2;
            Main m = new Main();
            switch (str) {
                case "加":
                    System.out.println("请输入两个数字,用\",\"分隔");
                    str2 = scanner.nextLine();
                    str1 = str2.split(",");//分隔
                    System.out.println(m.add(Double.valueOf(str1[0]), Double.valueOf(str1[1])));
                    break;
                case "减":
                    System.out.println("请输入两个数字,用\",\"分隔");
                    str2 = scanner.nextLine();
                    str1 = str2.split(",");//分隔
                    System.out.println(m.sub(Double.valueOf(str1[0]), Double.valueOf(str1[1])));
                    break;
                case "乘":
                    System.out.println("请输入两个数字,用\",\"分隔");
                    str2 = scanner.nextLine();
                    str1 = str2.split(",");//分隔
                    System.out.println(m.mutli(Double.valueOf(str1[0]), Double.valueOf(str1[1])));
                    break;
                case "除":
                    System.out.println("请输入两个数字,用\",\"分隔");
                    str2 = scanner.nextLine();
                    str1 = str2.split(",");//分隔
                    System.out.println(m.div(Double.valueOf(str1[0]), Double.valueOf(str1[1])));
                    break;
                default:
                    System.out.println("已退出");
                    flag = false;
            }
        }


    }

    public void pr() {

    }

    public double add(double a, double b) {
        //加
        return a + b;
    }

    public double sub(double a, double b) {
        //减
        return a - b;
    }

    public double mutli(double a, double b) {
        //乘
        return a * b;
    }

    public double div(double a, double b) {
        //除
        double c = 0.0;
        try {
            c = a / b;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return c;
    }


}
这篇关于【狂神说Java】练习的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!