用Java实现简单的四则运算

一、实验目的
学会用Java编写简单的四则运算。

二、实验原理及基本技术路线图(方框原理图)
通过所学知识编写程序,实现用户输入一个算式,通过运算输出结果。

三、所用仪器、材料(设备名称、型号、规格等)
Eclipse不限版本、JDK不限版本、配置环境变量

四、实验方法、步骤
思路分析:
首先拿到一个表达式后,我们如果按照人的计算方式,
有括号
在有括号的情况下,先计算得出括号中的结果。
没有括号
运算按照 先乘除,后加减进行。
1.没有括号的表达式实现
1.1.遍历运算符,如果运算符右边没有数字则报错,运算符左右都有数字则取出运算符左右的数字进行运算,然后将结果放回(当前索引位置)
2.有括号的表达式的实现
2.1.找到最内侧的括号内表达式,按照无括号的方法进行计算,将计算结果替换该括号表达式的位置,此时得到新的表达式,再继续递归调用当前方法。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class SimpleCompute {

	public static void main(String[] args) {
		// Define data types
		BufferedReader reader = null;
		InputStreamReader inputStreamReader = null;
		try {
			// Get user input
			System.out.println("Please enter expression: or enter # to end the operation! ");// Prompt the user for an expression
			inputStreamReader = new InputStreamReader(System.in);// Read input from the console
			reader = new BufferedReader(inputStreamReader);
			String str = reader.readLine(); // Read the information entered by the user
			while (!str.equals("#")) {
				System.out.println("The result of operation is:" + opt(str) + "");
				System.out.println("Please enter expression: or enter # to end the operation! ");
				str = reader.readLine();
			}
		}
		// When an exception is caught, it prints the trajectory of the exception
		catch (Exception e) {
			e.printStackTrace();
		}
		if (reader != null) {
			try {
				reader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static float opt(String s) throws Exception {
		if (s == null || "".equals(s.trim())) {
			return 0f;
		}
		//Gets the subscript of the first character after the operator
		int a1 = s.indexOf("+");
		int a2 = s.indexOf("-");
		int a3 = s.indexOf("*");
		int a4 = s.indexOf("/");
		int a5 = s.indexOf("(");
		//Determine if the formula is correct
		if (a1 == -1 && a2 == -1 && a3 == -1 && a4 == -1) {
			if (s.trim() == null || "".equals(s.trim())) {
				throw new Exception("operate error");
			}
			return Float.parseFloat(s.trim());
		}

		if (a5 != -1) {
			int a6 = s.indexOf(")");
			if (a6 == -1) {
				throw new Exception("Parentheses do not match");
			} else {
				float f = opt(s.substring(a5 + 1, a6).trim());
				s = s.replace(s.substring(a5, a6 + 1), String.valueOf(f));
				return opt(s);
			}
		}
		//Determines if there are characters on either side of the operator
		//Take the Numbers on both sides of the operator and perform the operation
		if (a1 != -1) {
			return opt(s.substring(0, a1)) + opt(s.substring(a1 + 1, s.length()));
		}
		if (a2 != -1) {
			return opt(s.substring(0, a2)) - opt(s.substring(a2 + 1, s.length()));
		}
		if (a3 != -1) {
			return opt(s.substring(0, a3)) * opt(s.substring(a3 + 1, s.length()));
		}
		if (a4 != -1) {
			return opt(s.substring(0, a4)) / opt(s.substring(a4 + 1, s.length()));
		}
		return Integer.parseInt(s.trim());
	}
}

运行结果:

Please enter expression: or enter # to end the operation! 
3+(3+3)*3
The result of operation is:21.0
Please enter expression: or enter # to end the operation! 
4+4*5
The result of operation is:24.0
Please enter expression: or enter # to end the operation! 

关于import java.util.ArrayList;的知识:
java.util.ArrayList是一个列表类,它是用来存放其他Java对象,内部是通过数组来实现的。
只要是java对象就可以往ArrayList里面放
java.util.ArrayList内部是通过数组来实现的:
当数组容量不够的时候,会对数组容量进行扩容可以通过数组下标来快速的访问ArrayList里面的元素
当新增或者删除ArrayList里面的元素时,可能会涉及到移位操作可以截取数组的子数组操作.
 定义如下:
public class ArrayList extends AbstractList
implements List, RandomAccess, Cloneable, java.io.Serializable{
//fields
//constructor
//methods
//inner class ‘Itr’
//inner class ‘ListItr’
//inner class ‘SubList’
}
java.util.ArrayList的常见属性:
//序列号
private static final long serialVersionUID = 8683452581122892189L;
//ArrayList实际存储元素的地方
private transient Object[] elementData;
//ArrayList中存储的元素个数
private int size;
//ArrayList最多存储元素的个数
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
//fast-fail失败机制标记
protected transient int modCount = 0;
构造方法:
第一种:默认构造方法(无参数构造方法)
public ArrayList()
第二种: 带初始列表容量大小参数的构造方法
public ArrayList(int initialCapacity)
第三种:带初始化子列表参数的构造方法
public ArrayList(Collection<? extends E> c)
常用方法:
修改操作:

boolean add(E e) 将指定的元素添加到此列表的尾部
void add(int index,E element) 将指定的元素插入此列表中的指定位置
E remove(int index) 移除此列表中指定位置上的元素
boolean remove(Object o) 移除此列表中首次出现的指定元素
E set(int index,E element) 用指定的元素替代此列表中指定位置上的元素
批量操作
boolean addAll(Collection<? extends E> c) 将子集合c中的元素添加到此集合中
boolean addAll(int index,Collection<? extends E> c) 将子集合c中的元素添加到此集合中的index位置开始处
void clear() 清空此集合
protected void removeRange(int fromIndex,int toIndex) 移除集合中索引在fromIndex(包括)和toIndex(不包括)之间的所有元素
public boolean removeAll(Collection<?> c) 移除此collection中那些也包含在指定collection中的所有元素
public boolean retainAll(Collection<?> c) 仅保留在子集合c中那些也包含在此集合中的元素
查询操作
boolean contains(Object o) 判断集合中是否包含了元素o
E get(int index) 返回此集合中index位置上的元素
int indexOf(Object o) 返回此集合中首次出现元素o的位置
boolean isEmpty() 判断此集合是否为空
int lastIndexOf(Object o) 返回此集合中最后一次出现元素o的位置
int size() 返回此集合中元素的个数
其他操作
Object clone() 返回此列表实例的浅复制
void ensureCapaCity(int minCapacity) 如有必要,增加此列表实例的容量,以确保它至少能够容纳最小容量参数所指定的元素数
void trimToSize() 将此列表实例的容量调整为列表的当前大小
数组操作
Object[] toArray() 按适当顺序返回包含此列表中所有元素的数组
T[] toArray(T[] a) 按适当顺序返回包含此列表中所有元素的数组
Iterator和子List操作
ListIterator listIterator(int index) 返回列表的ListIterator实例
ListIterator listIterator() 返回列表的ListIterator实例
Iterator iterator() 返回列表的Iterator实例
List subList(int fromIndex, int toIndex) 返回列表的子列表
ArrayList遍历方法:
支持三种遍历方式:

  1. 通过索引值去遍历(随机遍历)(效率最好)
  2. 通过增强的for循环去遍历(效率最低)
  3. 通过迭代器去遍历(效率次之)
  • 6
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

️雲野

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值