日期:2014-05-20 浏览次数:20821 次
package mypackage;
/**
* 该类用于实现一个简易计算器
* @author Administrator
* @version 1.0
*/
public class Caculator {
/**
* 保存输入的字符串
*/
String expression;
/**
* 保存运算符,即为 + ,- ,*, /中的一个
*/
String operator;
int number1;
int number2;
/**
* 获取输入字符串的函数
*/
void getExpression()
{
try
{
expression=new String();
this.expression=System.console().readLine();
}
catch(Exception e)
{
e.printStackTrace();
}
}
/**
* 获取分隔符函数
*/
void getOperation()
{
try{
operator=new String();
if(this.expression.indexOf('+')!=-1)
this.operator="\\+";
if(this.expression.indexOf('-')!=-1)
this.operator="-";
if(this.expression.indexOf('*')!=-1)
this.operator="\\*";
if(this.expression.indexOf('/')!=-1)
this.operator="/";
}
catch(Exception e)
{
e.printStackTrace();
}
}
/**
* 从字符串中得到数据元素
*/
void segmentation()
{
try{
String[] strArr=new String[2];
strArr=expression.split(this.operator);
number1=Integer.parseInt(strArr[0]);
number2=Integer.parseInt(strArr[1]);
}
catch(Exception e)
{
e.printStackTrace();
}
}
void caculate()
{
if(this.operator=="\\+")
System.out.println("="+(number1+number2));
if(this.operator=="-")
System.out.println("="+(number1-number2));
if(this.operator=="\\*")
System.out.println("="+(number1*number2));
if(this.operator=="/")
System.out.println("="+(number1/number2));
}
}
package mypackage;
public class Test {
public static void main(String[] args)
{
Caculator caculator=new Caculator();
caculator.getExpression();
caculator.getOperation();
caculator.segmentation();
caculator.caculate();
}
}
BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));