服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

一个简单的表达式求值类,java


  import java.util.date;
public class testcalc2
{
string a;
int len_of_str;
int err; //err 用于发现哪个字符是出错字符就是第一个出错字符串的下标,初始值为-1,表示无错
int index;

public testcalc2(string str)
{
a = str + "+";
len_of_str = a.length();
err = -1;
index = 0;
system.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%% " + a + len_of_str);

}

public double getnextnum()
{
int preindex = index, countofdot = 0;
if(a.charat(index) == '-')
index++;
if(!character.isdigit(a.charat(index)))
{
err = index;
return 0;
}
while((index < len_of_str) &&
(character.isdigit(a.charat(index)) || a.charat(index) == '.'))
{
if(a.charat(index) == '.')
{
countofdot++;
}
index++;
if(countofdot == 2)
{
err = index;

return 0;
}
}
return double.valueof(a.substring(preindex, index)).doublevalue();
}
public char getnextop()
{
char ch = a.charat(index);
if((ch != '+') && (ch != '-') && (ch != '*') && (ch != '/'))
{
err = index;
ch = ' ';
return ch;
}
index++;
return ch;

}
public double calcuvalue()
{
long start = system.currenttimemillis();
date d = new date();
long now = d.gettime(), dif;
char ch;
boolean minusflag = false, multiflag = false, dividflag = false;
double total = 0, next = 0, num = 0; //next used to be * or /
while(index < len_of_str)
{
num = getnextnum();
if(err != -1)
{
system.out.println("err!?! try to getnextnum but " +
" the char at index " + err + " is wrong ");
return 0;
}
system.out.println("index after " + index);

ch = getnextop();
if(err != -1)
{
system.out.println("err!?! try to getnextop but " +
" the char at index " + err + " is wrong ");
return 0;
}
system.out.println("index after " + index);

switch (ch)
{
case '+':

if(multiflag)
{
next = next * num;
}
else if(dividflag)
{
next = next / num;
}
else
{
next = num;
}
if(minusflag)
{
next = -next;
}
total = total + next;
minusflag = false;
multiflag = false;
dividflag = false;
break;
case '-':
if(multiflag)
{
next = next * num;
}
else if(dividflag)
{
next = next / num;
}
else
{
next = num;
}
if(minusflag)
{
next = -next;
}
total = total + next;
minusflag = true;
multiflag = false;
dividflag = false;
break;
case '*':
if(multiflag)
{
next = next * num;
}
else if(dividflag)
{
next = next / num;
}
else
{
next = num;
}
multiflag = true;
dividflag = false;
break;

case '/':
if(multiflag)
{
next = next * num;
}
else if(dividflag)
{
next = next / num;
}
else
{
next = num;
}
dividflag = true;
multiflag = false;
break;
default: //impossible ,already has err
}
system.out.println("ch " + ch + " num " + num + " total " + total +
" next " + next + " -" + minusflag + " *" +
multiflag + " /" + dividflag);
} //while

return total;

}

扫描关注微信公众号