Java写的有运算顺序的计算器(不含括号)
import import
public class Calculator
{
public static void main(String args[])throws Exception
{
int yunSuanFu;
float result;
String str = new BufferedReader(new InputStreamReader(System.in)).readLine();
char[] ch = str.toCharArray();
yunSuanFu = Tool.yunSuanFu(ch);
char[] fuHao = Tool.getFuHao(ch,yunSuanFu);
String[] sub = Tool.getSub(ch,str,yunSuanFu);
float[] zhi = Tool.getZhi(sub,yunSuanFu);
result = Tool.work(zhi,fuHao,yunSuanFu);
System.out.println(result);
}
}
class Tool
{
public static int yunSuanFu(char[] ch)
{
int i;
int yunSuanFu = 0;
for(i = 0; i < ch.length; i++){
if((ch[i] == '+') || (ch[i] == '-') || (ch[i] == '*') || (ch[i] == '/'))
{
yunSuanFu++;
}
}
return yunSuanFu;
}
public static char[] getFuHao(char[] ch, int yunSuanFu){
int i;
int j = 0;
char[] fuHao = new char[yunSuanFu];
for(i = 0; i < ch.length; i++){
if((ch[i] == '+') || (ch[i] == '-') || (ch[i] == '*') || (ch[i] == '/'))
{
fuHao[j] = ch[i];
j++;
}
}
return fuHao;
}
public static String[] getSub(char[] ch, String str, int yunSuanFu)
{
int i;
int j = 0;
int begin = 0;
String[] sub = new String[yunSuanFu+1];
for(i = 0; i < ch.length; i++){
if((ch[i] == '+') || (ch[i] == '-') || (ch[i] == '*') || (ch[i] == '/'))
{
sub[j] = str.substring(begin, i);
begin = i + 1;
j++;
}
}
sub[j] = str.substring(begin,ch.length);
return sub;
}
public static float[] getZhi(String[] sub, int yunSuanFu)
{
int i;
float[] zhi = new float[yunSuanFu+1];
for(i = 0; i <= yunSuanFu; i++)
{
zhi[i] = Float.parseFloat(sub[i]);
}
return zhi;
}
public static float work(float[] zhi, char[] fuHao, int yunSuanFu)
{
int k;
int tag = 0;
int index = 0;
float a;
float b;
for(k = 0; k < yunSuanFu; k++)
{
if((fuHao[k] == '+') || (fuHao[k] == '-'))
{
fuHao[index] = fuHao[k];
zhi[index+1] = zhi[k+1];
index++;
}
else if(fuHao[k] == '*')
{
if(tag + 1 == k)
{
zhi[index] = zhi[index] * zhi[k+1];
}
else
{
zhi[index] = zhi[k] * zhi[k+1];
}
tag = k;
}
else
{
if(tag + 1 == k)
{
zhi[index] = zhi[index] / zhi[k+1];
}
else
{
zhi[index] = zhi[k] / zhi[k+1];
}
tag = k;
}
}
if((fuHao[yunSuanFu-1] == '+') || (fuHao[yunSuanFu-1] == '-'))
{
zhi[index] = zhi[yunSuanFu];
}
a = zhi[0];
for(k = 0; k < index; k++)
{
b = zhi[k+1];
if(fuHao[k] == '+')
{
a += b;
}
else
{
a -= b;
}
}
return a;
}
}