Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Build a simple calculator that ignores order of operations. This “infix” calcula

ID: 674570 • Letter: B

Question

Build a simple calculator that ignores order of operations. This “infix” calculator will read in a String from the user and calculate the results of that String from left to right. Consider the following left-to- right calculations:

Example:

“4 + 4 / 2”
“Answer is 4” //not 6, since the addition occurs first when reading from left to right

Hints
Build the starter code using a snippet below.
Assume spaces between all numbers and operators
If a number is negative (like -3), there will be no space between the sign and the number
Use Scanner and nextInt() to read each integer
Use Scanner and what operation to read a single character? (our operator?)
You can also use StringTokenizer to do these tasks as well

// Driver code
public class calc {

public static void main( String[] args ) {
  
Scanner input = new Scanner( System.in );
  
System.out.println( "Enter the equation: " );
String question = input.nextLine();
  
int answer = calculate( input );
System.out.println( "Answer is " );
  
}

public static int calculate( String input ) {
  
int lhs,rhs; //short for left-hand & right-hand side char operation;
  
/*todo: your name and code goes here*/
/*You need a Scanner(or StringTokenizer) to get tokens
*Then you need a loop, and switch inside that loop*/
  
StringTokenizer tokens = new StringTokenizer(input, "{}()*/+-", true);
  
return lhs;
  
}
  
}

Explanation / Answer

public class calc {
public static void main( String[] args ) {
  
Scanner input = new Scanner( System.in );
  
System.out.println( "Enter the equation: " );
String question = input.nextLine();
  
int answer = calculate( input );
System.out.println( "Answer is "+answer );
  
}
public static int calculate( String input ) {
  
int i,j,len,lhs,rhs; //short for left-hand & right-hand side char operation;
len=input.length();

   for(i=0;i<len;i=i+2)
   {
       opr[i]=input.substring(i,1);
   }
   Scanner o = new Scanner(System.in);
   System.out.println("Enter token");
   String s=o.nextLine();

   switch(s)
   {
       case '+':
           lhs=opr[0]+opr[1];
           break;
  
       case '-':
           lhs=opr[0]-opr[1];
           break;  

       case '*':
           lhs=opr[0]*opr[1];
           break;

       case '/':
           lhs=opr[0]/opr[1];
           break;
   }
   return lhs;
  
}
  
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote