Pages

Monday, January 5, 2015

Arithmetic operation for given input string values as equation

package com;

import java.util.Scanner;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class Equation {

static Scanner s = new Scanner(System.in);

public static void main(String[] args) throws NullPointerException,
ScriptException {

String eq = null;

Scanner s = new Scanner(System.in);
System.out.println("enter the equation");
eq = s.nextLine();
char[] aa = eq.toCharArray();
String bb = new String();

for (int i = 0; i < aa.length; i++) {
if (aa[i] != '+' & aa[i] != '-' & aa[i] != '*' & aa[i] != '/'
& Character.isDigit(aa[i]) == false) {
bb = bb.concat(String.valueOf(insert(aa[i])));

}

else {
bb = bb.concat(String.valueOf(aa[i]));

}
}
System.out.println(bb);

ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
System.out.println("Result : "+engine.eval(bb));

}

private static int insert(char val) {

int a;
System.out.println("Enter the value of " + val + ": ");
a = s.nextInt();
return a;

}
}



OUTPUT:-

enter the equation
a*x+y*3+z*2
Enter the value of a: 
4
Enter the value of x: 
3
Enter the value of y: 
2
Enter the value of z: 
2
4*3+2*3+2*2
Result : 22.0

1 comment:

  1. Gambling Problem? Help Center, DNR, Resorts, Gambling
    This website 인천광역 출장샵 may harm your computer, causing computer to become 광명 출장마사지 infected or difficult to navigate. This is a common issue 남양주 출장안마 with many 동두천 출장마사지 casinos. 강릉 출장안마

    ReplyDelete