赞
踩
四则运算(10分)
题目内容:
你的程序要读入一个整数四则运算的式子,其中的整数均为非负整数且小于10000,其中的运算符只有加减乘除(+-/)四种。你的程序要计算这个式子,并输出结果。计算过程必须遵守优先级,即/要在+-之前先计算。当遇到除法时,按照Java语言的整数除法的方式来计算,即只留下整数的结果。
提示:一种可能的做法是,将整个式子作为字符串读入,然后找出其中最后一个+或-,在此位置将其截成两段,分别计算后再做+或-,以此类推。
另,用Integer.parseInt(s)可以从一个字符串得到整数。
输入格式:
输入时,所有的成分均没有有空格隔开,即每个运算符前后都没有空格。注意,单个数字也是可能的一种输入。
输出格式:
输出结果的整数。
输入样例:
2+3*4-6/3
输出样例:
12
import java.util.Scanner;
public class Main {
public static int find(String ch,int p)//找到乘除的位置
{
p++;
if(ch.indexOf('*',p)==-1)
{
p=ch.indexOf('/',p);
return p;
}
if(ch.indexOf('/',p)==-1)
{
p=ch.indexOf('*',p);
return p;
}
if(ch.indexOf('*',p)!=-1 && ch.indexOf('/',p)!=-1)
{
if(ch.indexOf('*',p) > ch.indexOf('/',p) )
{
p=ch.indexOf('/',p);
}
if(ch.indexOf('*',p) < ch.indexOf('/',p))
{
p=ch.indexOf('*',p);
}
}
else if(ch.indexOf('*',p)==-1 && ch.indexOf('/',p)==-1)
{
p=-1;
}
return p;
}
public static int md(String ch)
{
int a,b,n1=1;
if(ch.charAt(0)=='-' || ch.charAt(0)=='+')
{
if(ch.charAt(0)=='-')
{
n1=-1;
}
ch=ch.substring(1);
}
String c;
a=find(ch,0);
b=find(ch,a);
if(a!=-1)
{
c=ch.substring(0,a);
n1*=Integer.parseInt(c);
while(a!=-1)
{
if(ch.charAt(a)=='*')
{
if(b==-1)
{
n1=n1*Integer.parseInt(ch.substring(a+1));
break;
}
if(b!=-1)
{
n1=n1*Integer.parseInt(ch.substring(a+1, b));
}
}
if(ch.charAt(a)=='/')
{
if(b==-1)
{
n1=n1/Integer.parseInt(ch.substring(a+1));
break;
}
if(b!=-1)
{
n1=n1/Integer.parseInt(ch.substring(a+1, b));
}
}
a=b;
b=find(ch,b);
}
}
else
{
c=ch.substring(0);
n1*=Integer.parseInt(c);
}
return n1;
}
public static String divide(String str)
{
String ch=str;
int a,b;
a=str.lastIndexOf('+');
b=str.lastIndexOf('-');
if(a > b)//加更靠后
{
ch=str.substring(a);
}
else if(b > a)
{
ch=str.substring(b);
}
if(a==-1 && b==0)
{
int i;
for(i=1; i<str.length() && str.charAt(i)!='+' && str.charAt(i)!='-';i++);
ch=str.substring(0,i);
}
if(a==-1 && b==-1)//
{
int i;
for(i=0; i<str.length() && str.charAt(i)!='+' && str.charAt(i)!='-';i++);
ch=str.substring(0,i);
}
return ch;
}
public static String part(String str)
{
String ch=null;
int a,b;
a=str.lastIndexOf('+');
b=str.lastIndexOf('-');
if(a > b)
{
ch=str.substring(0, a);
}
if(b > a)
{
ch=str.substring(0, b);
}
if(a==-1 && b==0)
{
ch=null;
}
if(a==-1 && b==-1)//
{
ch=null;
}
return ch;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in=new Scanner(System.in);
String str,ch,c,num1,num2;
int i,j,sum=0,n1,n2,a,b;
str = in.nextLine();
while(str!=null)
{
ch=divide(str);
sum+=md(ch);
str=part(str);
}
System.out.println(sum);
}
}

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。