·您的位置: 首页 » 资源教程 » 编程开发 » JAVA、JSP » 一个简单的表达式求值类,java

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

类别: JAVA教程  评论数:0 总得分:0
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;

}





-= 资 源 教 程 =-
文 章 搜 索
关键词:
类型:
范围:
纯粹空间 softpure.com
Copyright © 2006-2008 暖阳制作 版权所有
QQ: 15242663 (拒绝闲聊)  Email: faisun@sina.com
 纯粹空间 - 韩国酷站|酷站欣赏|教程大全|资源下载|免费博客|美女壁纸|设计素材|技术论坛   Valid XHTML 1.0 Transitional
百度搜索 谷歌搜索 Alexa搜索 | 粤ICP备19116064号-1