制作计算器,包含+,-,*,/,可以与用户交互,且循环使用

使用scanner对象,制作一个计算器

package com.YouHaoXin.method;

import java.util.Scanner;

public class Demo09 {
    public static void main(String[] args) {
        //通过Scanner制作一个计算器,包含+,-,*,/,且可循环使用。
        while (true) {//建立一个无限循环,保持程序可以循环使用



            Scanner scanner = new Scanner(System.in);//等待输入
            Scanner scanner1 = new Scanner(System.in);//等待输入
            System.out.println("请输入要计算的两个数字:");
            int i = scanner.nextInt();//将输入的数字赋值给i
            int i1 = scanner.nextInt();//将输入的数字赋值给i1
            System.out.println("请输入您要计算的方式(+,-,*,/)");
            Scanner scanner2 = new Scanner(System.in);//等待输入
            String charset = scanner2.nextLine();//将输入的字符串赋值给charset

            switch (charset) {//匹配一个值,并输出
                case "+":
                    System.out.println("加法结果为:"+(test1(i, i1)));
                    break;
                case "-":
                    System.out.println("减法法结果为:"+(test2(i,i1)));
                    break;
                case "*":
                    System.out.println("乘法结果为:"+(test3(i, i1)));
                    break;
                case "/":
                    System.out.println("除法结果为:"+(test4(i, i1)));
                    break;
            }
        }
    }


    //加法
    public static int test1(int a,int b){
        return a+b;
    }
    //减法
    public static int test2(int a,int b){
        return a-b;
    }
    //乘法
    public static int test3(int a,int b){
        return a*b;
    }
    //除法
    public static double test4(double a,double b){
        if(b==0){
            System.out.println("输入错误,除法中b不能为:");
            return 0;
        }else{return a/b;}
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值