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

Using java how do I implement this basic calculator? I know it has to do with pa

ID: 668777 • Letter: U

Question

Using java how do I implement this basic calculator? I know it has to do with parsing a string but that is what confuses me the most.

Method Signature:       int solve(String input)

The format for the string input is: < Number >

< Number > is integer from 1 to 10000.

< Number > can contain leading zeros

< Operation > is Math operations: +, -, *, /

Return the result of operation

Example:

·        solve(“1+2”)

o   Returns: 3

·        solve(“3/2”)

o   Returns: 1

·        solve("000000000014/00000000002")

o   Returns: 7

no user input, so no need to eror check. The math expressions will be hard coded in main. How do I do this?

Explanation / Answer

public class SimpleCalculator{
int solve (String input)
{
int index;
String a="",b="";
if(input.contains("+"))
{
index=input.indexOf("+");
return (input.subString(0,index))+(input.subString(index+1));
}
else
if(input.contains("-"))
{
index=input.indexOf("-");
return (input.subString(0,index))-(input.subString(index+1));
}
else
if(input.contains("*"))
{
index=input.indexOf("*");
return (input.subString(0,index))*(input.subString(index+1));
}
else
if(input.contains("/"))
{
index=input.indexOf("/");
return (input.subString(0,index))/(input.subString(index+1));
}
}
public static void main(String args[]){
System.out.println(solve("1+2");
System.out.println(solve("3/2");
System.out.println(solve("1*2");
}
}

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