JavaSE面向对象——基础介绍-老杜javaDay16

it2023-01-19  52

 题目需求:编写一个计算器,实现加减乘除,涉及,java分支机构,封装,构造方法,java面向对象的创建,以及数据传参!

public class demo02 { /* * 编写一个计算器,实现减价乘除功能! * */ public static void main(String[] args){ demo02 x = new demo02(); java.util.Scanner s = new java.util.Scanner(System.in); System.out.println("请输入要计算数字:"); x.sun1 = s.nextInt(); x.sun2 = s.nextInt(); System.out.println("请选择计算方式:+-/*%:"); x.sun = s.next(); demo02 x1 = new demo02(x.sun1,x.sun2,x.sun); } //封装 private int sun1; private int sun2; private String sun; //get,set public void setSun1(int sun1) { this.sun1 = sun1; } public void setSun2(int sun2) { this.sun2 = sun2; } public void setSun(String sun) { this.sun = sun; } public int getSun1() { return sun1; } public int getSun2() { return sun2; } public String getSun() { return sun; } //有参数 public demo02(int sun1, int sun2, String sun) { this.sun1 = sun1; this.sun2 = sun2; this.sun = sun; switch(sun){ case "+": System.out.println("计算结果:"+(sun1+sun2)); break; case "-": System.out.println("计算结果:"+(sun1-sun2)); break; case "*": System.out.println("计算结果:"+(sun1*sun2)); break; case "/": System.out.println("计算结果:"+(sun1/sun2)); break; case "%": System.out.println("计算结果:"+(sun1%sun2)); break; } } //无参数 public demo02() { } }

 

最新回复(0)