JAVA大作业说明报告
- 表达式运算规则:
运算过程无优先级,从左到右进行运算。 - 程序功能说明:
程序只能计算(±*/)四种计算。 - 程序输入说明:
输入只能输入整数,例如如下
表达式:-2+3*(-5)/3-2*9
对于本程序不能识别的输入内容,(例如字母,其他符号)
输出:FORMAT ERROR!
对于运算过程中出现除 0 情况,输出:
Error:Divided by zero! - 程序计算结果的输出规格:
格式为(示例):-2+3*(-5)/3-2*9=-27
主函数:
package bighomework1;
import bighomework1.Calculate;
import java.util.Scanner;
public class demo_big1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.println("请输入运算式: ");
String s = input.nextLine();
String fina = Calculate.calculate(s);
System.out.print(fina);
}
}
计算方法calculate和检查合法方法test:
package bighomework1;
public class Calculate {
static int test1(String s,int l) //判断首尾字符
{
if(l<1)
return 0;
char c1 = s.charAt(0);
char c2 = s.charAt(l-1);
if(c1<'0'||c1>'9'||c2<'0'||c2>'9')
{
if(c1 == '-' && c2>'0'&&c2<'9' )
{
return 1;
}
else if(c2==')'&&c1>'0'&&c1<'9')
{
return 1;
}
else if(c2==')'&&c1=='-')
return 1;
else
return 0;
}
return 1;
}
static int test2(String s,int l) //判断内容
{
int flag = 1,left=0,right=0;
for(int i=0;i<l;i++)
{
char c = s.charAt(i);
if((c<'0'||c>'9')&&c!='*'&&c!='/'&&c!='+'&&c!='-'&&c!='('&&c!=')')
flag = 0;
if(c == ' ') //空格
flag = 0;
if(c == '(') //空括号
{
char c1 = s.charAt(i+1);
if(c1 == ')' ||c1 == '+' || c1 == '*' || c1 == '/')
flag = 0;
}
if(c == '(')
{
char c1 = s.charAt(i+1);
if(c1 == '(')
flag =0;
}
if(c == '+' || c == '-' || c == '*' || c == '/') //连续运算符
{
char c1 = s.charAt(i+1);
if(c1 == '+' || c1 == '-' || c1 == '*' || c1 == '/' || c1 == ')')
flag = 0;
if(c == '/' && c1 == '0')
flag = 2;
}
if(c == '(') //括号匹配
{
left++;
}
if(c == ')')
{
right++;
if(right>left)
{
flag = 0;
}
}
}
if(left != right)
flag = 0;
return flag;
}
static String calculate(String s) {
// String x = null;
int t1 = 0,t2 = 0;
long num = 0,echo = 0;
int l = s.length();
t1 = Calculate.test1(s, l);
if(t1 == 1)
{
t2 = Calculate.test2(s, l);
}
if(t1 == 0 || t2 == 0)
{
return "FORMAT ERROR!";
}
else if(t2 == 2)
{
return "ERROR:Divided by zero!";
}
else if(t1 == 1 && t2 == 1)
{
if(s.charAt(0)!='-')
echo = s.charAt(0)-48;
int ff = 1;
for(int i=0;i<l;i++)
{
char c = s.charAt(i);
if(c == '+'||c == '-'||c == '*'||c =='/'||i==0)
{
char c1;
for(int j=i+1;j<l;j++)
{
c1 = s.charAt(j);
if(c1 == '(')
{
j=j+2;
ff = 0;
c1 = s.charAt(j);
}
if(c1<'0'||c1>'9')
break;
else
echo = echo*10+c1-48;
}
if(ff == 0)
{
echo = -echo;
}
if(c == '-')
{
num = num - echo;
echo =0;
}
else if(c == '+'||i==0)
{
num = num + echo;
echo =0;
}
else if(c == '*')
{
num = num * echo;
echo =0;
}
else if(c == '/')
{
num = num / echo;
echo =0;
}
if(ff == 0)
{
i = i+2;
ff = 1;
}
}
}
}
String x =s+"="+num;
return x;
}
}