Write a simple \"calculator\" parser in java. Don\'t make this complicated. You
ID: 3877536 • Letter: W
Question
Write a simple "calculator" parser in java. Don't make this complicated. You will have input of the form:
number (operator number) (operator number) (operator number)...
where a number is just a string of digits (don't worry about signs, floating point numbers, scientific notation...)
and operator is one of +,-,*,/
Find each of the above tokens and identify it as a number or operator
For example, the input:
5 + 3 * 2
should output:
5 number
+ operator
3 number
* operator
2 number
You may assume that each token has at least one space between it and the next token
If you hit an error character you can either ignore it or terminate your program
Hand in your java source code.
Explanation / Answer
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
String input;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the string to parse");
input=sc.nextLine();
input=input.replace(" ","");
char[] tokens=input.toCharArray();
for(char token :tokens)
{
if(Character.isDigit(token))
{
System.out.println(token+" number");
}
else
System.out.println(token+" operator");
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.