最近学习了一下Java语言,用它写了个小计算器。当然,功能还很简单,感兴趣的朋友可以自己看看,或者交流。程序
有三部分组成:
首先主程序calculate.java传入字符串(如“2+8*6-5=”),代码如下:
import calculatelib.expression;
import calculatelib.calculator;
public class calculate
{
?public static void main(String[] args)
?{
? expression exp=new expression(args[0]);
? calculator compute=new calculator();
? int i=0;
? while(exp.data[i]!=null)
? {
? ?compute.data[i]=Integer.parseInt(exp.data[i]);
? ?i++;
? }
? i=1;
? while(exp.calcus[i]!='=')
? {
? ?compute.opt[i]=exp.calcus[i];
? ?i++;
? }
? compute.setbounds(exp.getdatalength(),exp.getcalcuslength());
? System.out.println("the answer of your expression:");
? System.out.print(args[0]);
? System.out.println(compute.calculate());?
?}
}
然后由通过对象调用expression中的方法完成最字符串的编辑:
package calculatelib;
public class expression
{
?public String data[]=new String[50];
?public char calcus[]=new char[50];
?int i=0,r=0,tmp=0;
?int cr=1,estop=0;
?public expression(String args)
?{
? String s=args;
? int sstop=s.length();
? char ch[]=s.toCharArray();
? int cstop=ch.length;
? while(i? {
? ?if(Character.isDigit(s.charAt(i)))
? ?{
? ? i++;
? ? continue;
? ?}
? ?data[r]=s.substring(tmp,i);
? ?i++;
? ?tmp=i;
? ?r++;
? }
? i=0;
? while(i? {
? ?if(!Character.isDigit(ch[i]))
? ?{
? ? calcus[cr]=ch[i];
? ? if(calcus[cr]=='-')
? ? {
? ? ?data[cr]='-'+data[cr];
? ? ?calcus[cr]='+';
? ? }
? ? cr++;
? ?}
? ?i++;
? }
?}
?public int getdatalength()
?{return r;}
?public int getcalcuslength()
?{return cr-2;}
}
形成操作数数组data[]和操作符数组calcus[]。然后由calculater类中的方法计算数组,并返回结果。源码如下:
package calculatelib;
public class calculator
{
?public float[] data=new float[50];
?public char[] opt=new char[50];
?int cstop=0,dstop=0;
?int i=0;
?public float calculate()
?{
? for(i=1;i? {
? ?if((opt[i]=='*')||(opt[i]=='/'))
? ?{
? ? switch(opt[i])
? ? {
? ? ?case'*':
? ? ?{
? ? ? data[i]=data[i-1]*data[i];
? ? ? data[i-1]=0;
? ? ? continue;
? ? ?}
? ? ?case'/':
? ? ?{
? ? ? data[i]=data[i-1]/data[i];
? ? ? data[i-1]=0;
? ? ? continue;
? ? ?}
? ? }
? ?}
? }
? for(i=0;i? ?data[i+1]=data[i]+data[i+1];
? return data[i];
?}
?public void setbounds(int d,int c)
?{
? cstop=c+1;
? dstop=d;
?}
}
有兴趣的朋友可以参考一下。