Write a simple case for the use of objects, properties and methods in Java
import java.util.Scanner; class Calculste { int a; //定义两个整数 int b; String option; //定义接收操作符的字符串 public void count(){ //对操作符进行判断 switch(option){ case "+": System.out.println("计算和:"+a+"+"+b+"="+(a+b)); break; case "-": System.out.println("计算差:"+a+"-"+b+"="+(a-b)); break; case "*": System.out.println("计算积:"+a+"*"+b+"="+(a*b)); break; case "/": { //作除法运算时,分母不能为 0 if (b != 0) { System.out.println("计算商:"+a+"/"+b+"="+(a/b)); }else{ System.out.println("您输入的第二个数不能为 0,请重新输入"); } } break; case "%": System.out.println("计算余:"+a+"%"+b+"="+(a%b)); break; default: System.out.println("您输入的操作符有误,请重新输入"); } } } class demo3 { //需求: 使用java类描述一个计算器类,计算器具备操作数1, 操作数2 、操作符三个公共 的属性,还具备计算的功能行为。 public static void main(String[] args) { System.out.println("两个数的运算"); Scanner sca = new Scanner(System.in); //创建类的对象 Calculste cal = new Calculste(); //给属性赋值 System.out.println("第一个数:"); cal.a = (int)sca.nextInt(); System.out.println("第二个数:"); cal.b = (int)sca.nextInt(); System.out.println("输入运算符号:"); cal.option = sca.next(); //接受字符的方法 //调用方法运算 cal.count(); } }
Here are some effects on the console:
Momo said: Java language is an object-oriented programming language. Classes, objects in classes, and object properties and methods are all very important.
The above is the entire content of this article. I hope it will be helpful to everyone's learning. I also hope that everyone will support the PHP Chinese website.
For more articles related to the calculator implementation code of simple practical cases of Java objects, please pay attention to the PHP Chinese website!