Java object simple practical case calculator implementation code
Jan 20, 2017 pm 04:56 PMWrite 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!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How does Java's classloading mechanism work, including different classloaders and their delegation models?

Top 4 JavaScript Frameworks in 2025: React, Angular, Vue, Svelte

How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?

Node.js 20: Key Performance Boosts and New Features

Iceberg: The Future of Data Lake Tables

Spring Boot SnakeYAML 2.0 CVE-2022-1471 Issue Fixed

How can I implement functional programming techniques in Java?
