二.接收用户输入的表达式,把操作数和运算符分开显示出来。
如:输入的表达式为:1+2
那么输出为:操作数:1 2
运算符:+
import java.io.IOException;
import java.util.Vector;
/**
* <p>Title:</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2006</p>
* <p>Company: </p>
* @author Alex Zhu
* @version 1.0
*/
public class SplitExpression {
public SplitExpression() {
}
public static void main(String[] args) {
try {
System.out.println("Input the expression please:");
String operand = new String();
String operator = new String();
byte[] buffer = new byte[255];
System.in.read(buffer);
String expression = new String(buffer).trim();
for(int i=0;i<expression.length();i++){
String eachCharactor = expression.substring(i, i + 1);
try {
Integer.parseInt(eachCharactor);
operand += eachCharactor;
}
catch (NumberFormatException ex1) {
operand +=" ";
if(eachCharactor.equals("+")||
eachCharactor.equals("-")||
eachCharactor.equals("*")||
eachCharactor.equals("/")||
eachCharactor.equals("%")){
operator += eachCharactor + " ";
}else{
System.out.println("Expression["+expression+"]'s operator was wrong!");
System.exit(0);
}
}
}
System.out.println("Operand: "+operand);
System.out.println("Operator: "+operator);
}
catch (IOException ex) {
}
}
}
如:输入的表达式为:1+2
那么输出为:操作数:1 2
运算符:+
import java.io.IOException;
import java.util.Vector;
/**
* <p>Title:</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2006</p>
* <p>Company: </p>
* @author Alex Zhu
* @version 1.0
*/
public class SplitExpression {
public SplitExpression() {
}
public static void main(String[] args) {
try {
System.out.println("Input the expression please:");
String operand = new String();
String operator = new String();
byte[] buffer = new byte[255];
System.in.read(buffer);
String expression = new String(buffer).trim();
for(int i=0;i<expression.length();i++){
String eachCharactor = expression.substring(i, i + 1);
try {
Integer.parseInt(eachCharactor);
operand += eachCharactor;
}
catch (NumberFormatException ex1) {
operand +=" ";
if(eachCharactor.equals("+")||
eachCharactor.equals("-")||
eachCharactor.equals("*")||
eachCharactor.equals("/")||
eachCharactor.equals("%")){
operator += eachCharactor + " ";
}else{
System.out.println("Expression["+expression+"]'s operator was wrong!");
System.exit(0);
}
}
}
System.out.println("Operand: "+operand);
System.out.println("Operator: "+operator);
}
catch (IOException ex) {
}
}
}