java求讲解

publicclassA4Q2{publicA4Q2(){}publicvoidevaluateExpressionsOnePerLine(){Scanners=newS... public class A4Q2
{
public A4Q2(){

}
public void evaluateExpressionsOnePerLine(){
Scanner s = new Scanner(System.in);
System.out.println("enter an expression and I'll display the result, or press end-of-file to exit");
while (s.hasNext()){
System.out.println("result = " + evaluateExpression(s.nextLine()) );
System.out.println("enter an expression and I'll display its result, or press end-of-file to exit");
}
System.out.println("Exiting");
}
private int evaluateExpression(String line){
line = replaceOperators(line);
return result(line);
}
private int result(String line){
// set up scanner and process the line
Scanner sl = new Scanner(line);
int result = sl.nextInt(); // first operand
// for each operator and operand
// apply the operator to its operands
while (sl.hasNext()){
String opr = sl.next();
int operand = sl.nextInt();
switch(opr){
case "+": result = result + operand;
break;
case "-": result = result - operand;
break;
case "*": result = result * operand;
break;
case "/": result = result / operand;
break;
case "%": result = result % operand;
break;
}
}
return result;
}

private String replaceOperators(String line){
String lineWithSPace = "";
for (int i=0; i<line.length(); i++){
char c = line.charAt(i);
switch (c) {
case '+':
lineWithSPace += " + ";
break;

case '*':
lineWithSPace += " * ";
break;

case '%':
lineWithSPace += " % ";
break;

case '-':
lineWithSPace += " - ";
break;

case '/' :
lineWithSPace += " / ";
break;

default:
lineWithSPace += c;
}
}
return lineWithSPace;
}
}
希望能有个大佬能够详细的讲解一下上面这个程序。我对代码分块感到无力。
展开
 我来答
龙少尘
2018-04-17 · TA获得超过1394个赞
知道小有建树答主
回答量:605
采纳率:78%
帮助的人:179万
展开全部
当执行方法evaluateExpressionsOnePerLine的时候,调用了其中的evaluateExpression方法并传入了参数,这个参数是自己输入的。接着进入方法evaluateExpression执行时,先调用了方法replaceOperators,并将输入的参数传入,然后调用方法result,并将执行方法replaceOperators的结果当做参数传入。最后将方法result执行的结果输出。
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式