美文网首页
Java实现简单的计算器(加减乘除)

Java实现简单的计算器(加减乘除)

作者: 明小五 | 来源:发表于2020-06-11 15:28 被阅读0次
    package test;
    
    import java.util.Scanner;
    
    public class Caculater {
        public static void computer(){
            Scanner scanner=new Scanner(System.in);
            int a=0;
            System.out.println("请输入第一个数字:");
            while(true){
                String line = scanner.nextLine();
                try {
                    a=Integer.parseInt(line);
                    break;
                } catch (Exception e) {
                    System.out.println("输入错误,请重新输入:");
    
                }
            }
            System.out.println("请输入运算符:");
            String operator=null;
            while(true){
                operator = scanner.nextLine();
    
                if (!"+".equals(operator)&&!"-".equals(operator)&&
                        !"*".equals(operator)&&!"/".equals(operator)) {
                    System.out.println("请输入正确的运算符:");
    
                }else {
                    break;
                }
            }
            System.out.println("请输入第二个数字:");
            int b = 0;
            while(true){
                String line = scanner.nextLine();
                try {
                    b=Integer.parseInt(line);
                    if ("/".equals(operator)&&b==0) {
                        throw new Exception();
                    }
                    break;
                } catch (Exception e) {
                    System.out.println("输入错误,请重新输入:");
    
                }
            }
            if ("+".equals(operator)) {
                System.out.println("运算结果为:"+(a+b));
            }else  if("-".equals(operator)){
                System.out.println("运算结果为:"+(a-b));
            }else if ("*".equals(operator)) {
                System.out.println("运算结果为:"+(a*b));
            }else {
                System.out.println("运算结果为:"+(a/b));
            }
        }
    
        public static void main(String [] args){
            Caculater.computer();
        }
    
    }
    
    
    
    

    相关文章

      网友评论

          本文标题:Java实现简单的计算器(加减乘除)

          本文链接:https://www.haomeiwen.com/subject/gvpbtktx.html