题目的要求是:用户输入一个运算式后回车,出现结果.例如,输入"1+2",回车,输出3;输入"140/2",回车,输出70.以下是我的未完成的程序:
import java.io.*;
public class Calculation {
public static void main(String args[]) throws IOException{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
String str=br.readLine();
int length=str.length();
int operand1,operand2,result=0;
String oper1="",oper2="";
boolean afterOper1=false;
char c,flag='0';
for(int i=0;i<length;i++){
c=str.charAt(i);
if(c!='+' && c!='-' && c!='*' && c!='/'){
if(!afterOper1){
oper1+=c;
}else{
oper2+=c;
}
}else{
afterOper1=true;
flag=c;
}
}
operand1=Integer.parseInt(oper1);
operand2=Integer.parseInt(oper2);
switch(flag){
case'+':result=operand1+operand2;break;
case'-':result=operand1-operand2;break;
case'*':result=operand1*operand2;break;
case'/':result=operand1/operand2;break;
}
System.out.println(result);
}
}
在这段代码里面,我只完成了两个操作数都是正数的情况.但是当操作数为负数时,我想加入符号位来判断.下面的代码是我修改后的代码:
import java.io.*;
public class Calculation {
public static void main(String args[]) throws IOException{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
String str=br.readLine();
int length=str.length();
int operand1,operand2,result=0;
String oper1="",oper2="";
boolean afterOper1=false;
char c,flag='0';
for(int i=0;i<length;i++){
c=str.charAt(i);
if(c!='+' && c!='-' && c!='*' && c!='/'){
if(!afterOper1){
oper1+=c;
}else{
oper2+=c;
}
}else{
afterOper1=true;
flag=c;
}
}
c=oper1.charAt(0);//取出第一个操作数的首位来判断是数字还是负号
System.out.println(c);//当输入的第一个操作数有负号时,报错
operand1=Integer.parseInt(oper1);
operand2=Integer.parseInt(oper2);
switch(flag){
case'+':result=operand1+operand2;break;
case'-':result=operand1-operand2;break;
case'*':result=operand1*operand2;break;
case'/':result=operand1/operand2;break;
}
System.out.println(result);
}
}
上面的代码也是未完成,因为我想判断第一个操作数的符号时出现了错误.例如,当输入"-3+2"时,报错:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at src.Calculation.main(Calculation.java:28)
百思不得其解,请教高手为什么会这样?