Compiler Type Promotion - casting

I am making a compiler as an exercise before applying to jobs, and am working by myself but following a college course website (thus I have already graduated, this is not schoolwork).
Currently, I am unsure how to resolve typecasting with post-fix notation. If I have:
"1.0 plus 2 equals" + 1.0 + 2
and
1+2/(3-4)
Then in post fix notation, I can obtain
STR[1,0]:"1.0 plus 2 equals"
DBL[1,22]:1.0
INT[1,28]:2
ADD[1,26]:+
ADD[1,20]:+
and
INT[0,0]:1
INT[0,2]:2
INT[0,5]:3
INT[0,7]:4
SUB[0,6]:-
DIV[0,3]:/
ADD[0,1]:+
I am unsure of how to evaluate the first. Currently I have assumed everything to (incorrectly) be doubles and have obtained this code (under Compiler.java):
static Object evaluate(List<Token> tokens)
{
Stack<Double> stack = new Stack<>();
for (Token token : tokens)
{
if (token.isEX())
stack.push(Double.parseDouble(token.getLexeme()));
else
{
Double a = stack.pop();
Double b = stack.pop();
switch (token.getType())
{
case ADD:
stack.push(b+a);
break;
case SUB:
stack.push(b-a);
break;
case MUL:
stack.push(b*a);
break;
case DIV:
stack.push(b/a);
break;
case MOD:
stack.push(b%a);
break;
}
}
}
return stack.pop();
}
I can correctly evaluate the second to -1, but this has two obvious problems, it promotes an integer when it doesn't need to, and it doesn't work for string concatenation.
A direct answer would be nice, but some hints/websites or guides would be greatly appreciated instead.
Here are the files for understanding this code (though it is generic to many other homemade compilers):
Compiler.java:
import java.util.List;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Compiler
{
/**
* Converts code string to direct stack of tokens
*
* #param line source of code
* #param lineNum line number
* #return stack of tokens in line order
*/
static Stack<Token> tokenize(String line, int lineNum)
{
Stack<Token> tokens = new Stack<>();
Pattern p = Pattern.compile(Token.regex);
Matcher m = p.matcher(line);
while (m.find())
tokens.push(new Token(m.group(), lineNum, m.start()));
return tokens;
}
/**
* Formats stack of tokens to postfix notation (Shunting-Yard Algorithm)
*
* #param tokens to be added.
* #return stack tokens in postfix notation
*/
static Stack<Token> format(Stack<Token> tokens)
{
Stack<Token> out = new Stack<>();
Stack<Token> tmp = new Stack<>();
for (Token token : tokens)
{
Token.Type type = token.getType();
if (type.rank > 0) // if token is operation
{
while (!tmp.isEmpty() && tmp.peek().getType().rank > type.rank)
out.add(tmp.pop());
tmp.push(token);
}
else if (type == Token.Type.LPR)
tmp.push(token);
else if (type == Token.Type.RPR)
{
while (tmp.peek().getType() != Token.Type.LPR)
out.add(tmp.pop());
tmp.pop();
}
else
out.add(token);
}
while (!tmp.isEmpty())
out.add(tmp.pop());
return out;
}
static Object evaluate(List<Token> tokens)
{
Stack<Double> stack = new Stack<>();
for (Token token : tokens)
{
if (token.isEX())
stack.push(Double.parseDouble(token.getLexeme()));
else
{
// TODO: don't just assume it's double here?
Double a = stack.pop();
Double b = stack.pop();
// TODO: only allow add if either token is a string
switch (token.getType())
{
case ADD:
stack.push(b+a);
break;
case SUB:
stack.push(b-a);
break;
case MUL:
stack.push(b*a);
break;
case DIV:
stack.push(b/a);
break;
case MOD:
stack.push(b%a);
break;
}
}
}
return stack.pop();
}
}
Token.java:
public class Token
{
enum Type
{
LSH(3, "<<"), // Left shift
RSH(3, ">>"), // Right shift
MUL(2, "\\*"), // Multiply
DIV(2, "/"), // Divide
MOD(2, "/"), // Modulo
ADD(1, "\\+"), // Add
SUB(1, "-"), // Subtract
DBL("\\d+\\.\\d*"), // Double
INT("\\d+"), // Integer
STR("\".*\""), // String
LPR("\\("), // Left parenthesis
RPR("\\)"), // Right parenthesis
;
//REF(0, "\\w+(\\.\\w+)+"),
final String symbol;
final int rank;
Type(String symbol)
{
this.symbol = symbol;
this.rank = 0;
}
Type(int rank, String symbol)
{
this.symbol = symbol;
this.rank = rank;
}
}
/**
* Regular expression for expressions and operations
*/
final static String regex;
static
{
StringBuilder sb = new StringBuilder();
Type[] t = Type.values();
for (int i = 0; i < t.length; i++)
{
if (i != 0)
sb.append('|');
sb.append(t[i].symbol);
}
regex = sb.toString();
}
/**
* Text literal
*/
private String lexeme;
/**
* Expression/operation type
*/
private Type type;
/**
* line number
*/
private int lineNum;
/**
* character number
*/
private int posNum;
/**
* Creates a token with debugging information
*
* #param lexeme Text literal
* #param lineNum Line number
* #param posNum Character number
* #return Token with processed type of lexeme
*/
Token(String lexeme, int lineNum, int posNum)
{
this.lexeme = lexeme;
for (Type type : Type.values())
if (lexeme.matches(type.symbol))
{
this.type = type;
break;
}
this.lineNum = lineNum;
this.posNum = posNum;
}
boolean isEX()
{
return type.rank == 0;
}
boolean isOP()
{
return type.rank > 0;
}
String getLexeme()
{
return lexeme;
}
Type getType()
{
return type;
}
public int getLineNum()
{
return lineNum;
}
public int getPosNum()
{
return posNum;
}
#Override
public String toString()
{
return String.format("%s[%d,%d]:%s", type, lineNum, posNum, lexeme);
}
}
Driver.java (for some simple test cases):
import java.util.Stack;
public class Driver
{
public static void main(String[] args)
{
String simpleTest = "1+2/(3-4)";
Stack<Token> tokens;
tokens = Compiler.format(Compiler.tokenize(simpleTest, 0));
System.out.println("Simple Test");
tokens.forEach(System.out::println);
System.out.println(Compiler.evaluate(tokens));
String hardTest = "\"1.0 plus 2 equals\" + 1.0 + 2";
tokens = Compiler.format(Compiler.tokenize(hardTest, 1));
System.out.println("\nHard Test");
tokens.forEach(System.out::println);
}
}

Related

How do I only import the class from a module once [duplicate]

This question already has answers here:
What is causing the "error LNK2005: already defined in .obj" s errors in my code?
(1 answer)
What does this error mean and how do I solve it: error LNK2005: "<symbol>" already defined in <file.obj>
(1 answer)
Closed 2 months ago.
I'm trying to import a lightweight maths parsing library. It is only available as a .cpp file. (this is the library)
When I import it using #include mathparser.cpp, I get loads of LNK2005 errors, saying it is defining all the class methods again.
I'm not actually defining them in the main file though, why might these errors be occuring, and what should I do to fix them?
You should never #include a cpp file. You should include header files, and ensure they have header guards (or use #pragma once). In this case the mathparser.cpp should be split up such that the parser class is in its own header and cpp file, then just main is in the cpp file.
mathparser.h
#pragma once
#include < iostream >
#include < cstdlib >
#include < cctype >
#include < cstring >
#include < math.h >
#define PI 3.14159265358979323846
using namespace std;
enum types { DELIMITER = 1, VARIABLE, NUMBER, FUNCTION };
const int NUMVARS = 26;
class parser {
char *exp_ptr; // points to the expression
char token[256]; // holds current token
char tok_type; // holds token's type
double vars[NUMVARS]; // holds variable's values
void eval_exp1(double &result);
void eval_exp2(double &result);
void eval_exp3(double &result);
void eval_exp4(double &result);
void eval_exp5(double &result);
void eval_exp6(double &result);
void get_token();
public:
parser();
double eval_exp(char *exp);
char errormsg[64];
};
mathparser.cpp
#include "stdafx.h"
#include "mathparser.h"
// Parser constructor.
parser::parser()
{
int i;
exp_ptr = NULL;
for (i = 0; i < NUMVARS; i++)
vars[i] = 0.0;
errormsg[0] = '\0';
}
// Parser entry point.
double parser::eval_exp(char *exp)
{
errormsg[0] = '\0';
double result;
exp_ptr = exp;
get_token();
if (!*token)
{
strcpy(errormsg, "No Expression Present"); // no expression present
return (double)0;
}
eval_exp1(result);
if (*token) // last token must be null
strcpy(errormsg, "Syntax Error");
return result;
}
// Process an assignment.
void parser::eval_exp1(double &result)
{
int slot;
char temp_token[80];
if (tok_type == VARIABLE)
{
// save old token
char *t_ptr = exp_ptr;
strcpy(temp_token, token);
// compute the index of the variable
slot = *token - 'A';
get_token();
if (*token != '=')
{
exp_ptr = t_ptr; // return current token
strcpy(token, temp_token); // restore old token
tok_type = VARIABLE;
}
else {
get_token(); // get next part of exp
eval_exp2(result);
vars[slot] = result;
return;
}
}
eval_exp2(result);
}
// Add or subtract two terms.
void parser::eval_exp2(double &result)
{
register char op;
double temp;
eval_exp3(result);
while ((op = *token) == '+' || op == '-')
{
get_token();
eval_exp3(temp);
switch (op)
{
case '-':
result = result - temp;
break;
case '+':
result = result + temp;
break;
}
}
}
// Multiply or divide two factors.
void parser::eval_exp3(double &result)
{
register char op;
double temp;
eval_exp4(result);
while ((op = *token) == '*' || op == '/')
{
get_token();
eval_exp4(temp);
switch (op)
{
case '*':
result = result * temp;
break;
case '/':
result = result / temp;
break;
}
}
}
// Process an exponent.
void parser::eval_exp4(double &result)
{
double temp;
eval_exp5(result);
while (*token == '^')
{
get_token();
eval_exp5(temp);
result = pow(result, temp);
}
}
// Evaluate a unary + or -.
void parser::eval_exp5(double &result)
{
register char op;
op = 0;
if ((tok_type == DELIMITER) && *token == '+' || *token == '-')
{
op = *token;
get_token();
}
eval_exp6(result);
if (op == '-')
result = -result;
}
// Process a function, a parenthesized expression, a value or a variable
void parser::eval_exp6(double &result)
{
bool isfunc = (tok_type == FUNCTION);
char temp_token[80];
if (isfunc)
{
strcpy(temp_token, token);
get_token();
}
if ((*token == '('))
{
get_token();
eval_exp2(result);
if (*token != ')')
strcpy(errormsg, "Unbalanced Parentheses");
if (isfunc)
{
if (!strcmp(temp_token, "SIN"))
result = sin(PI / 180 * result);
else if (!strcmp(temp_token, "COS"))
result = cos(PI / 180 * result);
else if (!strcmp(temp_token, "TAN"))
result = tan(PI / 180 * result);
else if (!strcmp(temp_token, "ASIN"))
result = 180 / PI*asin(result);
else if (!strcmp(temp_token, "ACOS"))
result = 180 / PI*acos(result);
else if (!strcmp(temp_token, "ATAN"))
result = 180 / PI*atan(result);
else if (!strcmp(temp_token, "SINH"))
result = sinh(result);
else if (!strcmp(temp_token, "COSH"))
result = cosh(result);
else if (!strcmp(temp_token, "TANH"))
result = tanh(result);
else if (!strcmp(temp_token, "ASINH"))
result = asinh(result);
else if (!strcmp(temp_token, "ACOSH"))
result = acosh(result);
else if (!strcmp(temp_token, "ATANH"))
result = atanh(result);
else if (!strcmp(temp_token, "LN"))
result = log(result);
else if (!strcmp(temp_token, "LOG"))
result = log10(result);
else if (!strcmp(temp_token, "EXP"))
result = exp(result);
else if (!strcmp(temp_token, "SQRT"))
result = sqrt(result);
else if (!strcmp(temp_token, "SQR"))
result = result*result;
else if (!strcmp(temp_token, "ROUND"))
result = round(result);
else if (!strcmp(temp_token, "INT"))
result = floor(result);
else
strcpy(errormsg, "Unknown Function");
}
get_token();
}
else
switch (tok_type)
{
case VARIABLE:
result = vars[*token - 'A'];
get_token();
return;
case NUMBER:
result = atof(token);
get_token();
return;
default:
strcpy(errormsg, "Syntax Error");
}
}
// Obtain the next token.
void parser::get_token()
{
register char *temp;
tok_type = 0;
temp = token;
*temp = '\0';
if (!*exp_ptr) // at end of expression
return;
while (isspace(*exp_ptr)) // skip over white space
++exp_ptr;
if (strchr("+-*/%^=()", *exp_ptr))
{
tok_type = DELIMITER;
*temp++ = *exp_ptr++; // advance to next char
}
else if (isalpha(*exp_ptr))
{
while (!strchr(" +-/*%^=()\t\r", *exp_ptr) && (*exp_ptr))
*temp++ = toupper(*exp_ptr++);
while (isspace(*exp_ptr)) // skip over white space
++exp_ptr;
tok_type = (*exp_ptr == '(') ? FUNCTION : VARIABLE;
}
else if (isdigit(*exp_ptr) || *exp_ptr == '.')
{
while (!strchr(" +-/*%^=()\t\r", *exp_ptr) && (*exp_ptr))
*temp++ = toupper(*exp_ptr++);
tok_type = NUMBER;
}
*temp = '\0';
if ((tok_type == VARIABLE) && (token[1]))
strcpy(errormsg, "Only first letter of variables is considered");
}
main.cpp
#include "mathparser.h"
int main()
{
char expstr[256];
parser ob;
cout << "Math expression parser. Enter a blank line to stop.\n\n";
do
{
cout << "Enter expression: ";
cin.getline(expstr, 255);
double ans = ob.eval_exp(expstr);
if (*ob.errormsg)
cout << "Error: " << ob.errormsg << "\n\n";
else
cout << "Answer: " << ans << "\n\n";
} while (*expstr);
return 0;
}
Then in your code you can #include "mathparser.h" to instantiate the parser class for your purposes.
Note that this code itself is full of poor practices and therefore a bad reference to study for learning modern C++, but that is outside the scope of your current question.

Failing to parse different math operators

This question is a follow-up from this one. Basically I'm trying to make a parser which calculates the total result of a string. 5+5+3*2/1 should give 16. This already works for strings only containing plusses and mins, so -55-44+1-2+123-54442+327737+1-2 successfully gives 273317.
It however does not work when plusses/mins get mixed with times/divides. So 1*2-2*3 returns 6 instead of -4. I think this is because I try to respect the order in which math needs to be executed (first plusses and mins, than times and division), but the operator somehow doesn't get updated.
#include <iostream>
#include <string>
#include <algorithm>
//Enumeration of all the possible
//math operators
enum Operator {
PLUS,
MIN,
TIMES,
DIVIDE,
UNDEFINED
};
/************************IGNORE********************/
char operatorToChar(Operator o) {
switch(o) {
case Operator::PLUS:
return '+';
break;
case Operator::MIN:
return '-';
break;
case Operator::TIMES:
return '*';
break;
case Operator::DIVIDE:
return '/';
break;
default:
return '0';
break;
}
}
/***************************************************/
/*
* Function to check if there are still times- or divide-operators in the action string.
* This to respect the order of math (first times and divides, than plusses and mins)
*
* :param action: The action string
* :return bool: Returns true if a '*' or '/' is found
*/
bool timesAndDividesGone(std::string& action) {
for (char& c : action) {
if (c == '*' || c == '/') {
return false;
}
}
return true;
}
/*
* Function to convert char to Operator
* :param c: One of the following '+', '-', '*', '/'
* :return Operator: Operating matching the character
*/
Operator charToOperator(char c) {
switch(c) {
case '+':
return Operator::PLUS;
break;
case '-':
return Operator::MIN;
break;
case '*':
return Operator::TIMES;
break;
case '/':
return Operator::DIVIDE;
break;
default:
return Operator::UNDEFINED;
break;
}
}
/*
* Function to do maths on two numbers, the math to do is decided by the operator
* :param x: First number
* :param y: Second number
* :param o: Operator (Plus, Min, Times or Divide)
* :return double: Result of the calculation
*
* Example:
* math(5, 5, Operator::Plus) == 10
*
*/
double math(double x, double y, Operator o) {
double z = 0;
switch (o) {
case Operator::PLUS:
z = x + y;
break;
case Operator::MIN:
z = x - y;
break;
case Operator::TIMES:
z = x * y;
break;
case Operator::DIVIDE:
z = x / y;
break;
}
return z;
}
/*
* Recursive function performing all the calculations from an action string.
* For example, if the string actions has value "5+7" in the first recursive run
* result should contain 12 after the last recursion.
*
* :param result: Double containing the calculated result after the last recursion
* :param actions: Action string (what you type in your calculator; e.g: 5+5). We analyze the first character of this string each time and add it to first_nr, second_nr, or make it the operator. First character gets deleted after each recursion
* :param first_nr: Empty at first recursion, number of left side of the operator. So in 55+77 this paramater will be "55". Gets resetted at the next operator
* :param second_nr: Idem as first_nr but for the right side of the operator.
* :param oper: Operation to calculate the first_nr and second_nr
*/
double calculate(double& result, std::string& actions, std::string& first_nr, std::string& second_nr, Operator& oper) {
//DEBUG OUTPUT:
std::cout << actions << " Gives ";
std::cout << std::to_string(result) << std::endl;
//Base-condition:
//If action string is empty return
if (actions == "") {
//Scenario for when first action is an operator
//e.g: 1+1-
if (second_nr == "")
second_nr = "0";
//Update result
result = math(std::stod(first_nr), std::stod(second_nr), oper);
return result;
}
//Get first character from action string
char c = actions[0];
//Making sure order of math is respected (first times and divdes)
//and than plus and min
char operatorInChar[4] = {'*', '/'};
if (timesAndDividesGone(actions)) {
operatorInChar[2] = '+';
operatorInChar[3] = '-';
}
//If first character is an operator
if (std::find(std::begin(operatorInChar), std::end(operatorInChar), c) != std::end(operatorInChar)) {
//Scenario for when first action is an operator
//e.g: -1+1
if (first_nr == "") {
if (actions[1] == '*')
first_nr = "1";
else
first_nr = "0";
}
//If operator is not yet set in a previous recursion
if (oper == Operator::UNDEFINED) {
oper = charToOperator(c);
//If second_nr is not empty, we need to calculate the two numbers together
if (second_nr != "") {
//Update result
result = math(std::stod(first_nr), std::stod(second_nr), oper);
}
} else {
//Update result
result = math(std::stod(first_nr), std::stod(second_nr), oper);
first_nr = std::to_string(result);
second_nr = "";
//Remove first character from action string because it's analysed in this recursion
actions = actions.erase(0, 1);
oper = charToOperator(c);
return calculate(result, actions, first_nr, second_nr, oper);
}
} else {
//If the character is not a operator but a number we append it to the correct nr
//we add to first_nr if the operator is not yet set, if we already encountered an operator
//we add to second_nr.
//e.g: actions = "123+789"
if (oper == Operator::UNDEFINED) {
first_nr += c;
} else {
second_nr += c;
}
}
//Remove first character from action string because it's analysed in this recursion
actions = actions.erase(0, 1);
//DEBUG OUTPUT:
//std::cout << first_nr << operatorToChar(oper) << second_nr << std::endl;
//std::cout << std::endl << actions << " Gives ";
//std::cout << std::to_string(result) << std::endl;
//Make recursive call
return calculate(result, actions, first_nr, second_nr, oper);
}
int main() {
//String we want to calculate
std::string str = "1*2-2*3";
std::string str_copy_for_output = str;
//Variables
double result = 0;
std::string first_nr = "";
std::string second_nr = "";
Operator oper = Operator::UNDEFINED;
//Call function
int calculation = calculate(result, str, first_nr, second_nr, oper);
//Output
std::cout << std::endl << str_copy_for_output << " = " << calculation << std::endl;
return 0;
}
tl;dr
This code works perfectly for strings only containing plusses and mins or only times and divides. Combining times and divides messes it up. Probably the operator parameter fails to update. How to fix this?
I'm sorry if I did not not analyze your code in detail because it is way too much complicated for what you are trying to do. Therefore I will not tell you where is exactly the problem, instead I will propose you something more simple.
One way or another you need to manage a stack because an algebraic expression must be handled as a tree structure and the evaluation process has to follow that structure. It can't be handled as a flat structure and you can't escape the management of operator precedence. In addition to that an expression is normally evaluated from left to right (left associativity).
That said if you really don't want to use a parsing tool (which IMHO would be more simple and clean), it is always possible to parse "manually". In that case you may avoid to manage an explicit stack by using the call stack itself as demonstrated in the following code:
#include <iostream>
int precedenceOf(char op) {
switch (op) {
case '+':
case '-':
return 4;
case '*':
case '/':
return 3;
}
return 0; // never happen
}
const int MAX_PRECEDENCE = 4;
double computeOp(double left, double right, char c) {
switch (c) {
case '+': return left + right;
case '-': return left - right;
case '*': return left * right;
case '/': return left / right;
}
return 0; // never happen
}
char readOperator(const char*& expr)
{
// read the operator
while (*expr != 0) {
switch (*expr) {
case '+':
case '-':
case '*':
case '/':
{
char res = *expr;
expr++;
return res;
}
case ' ':
break;
}
expr++;
}
return 0;
}
double readOperand(const char*& expr)
{
double result = 0;
while (*expr != 0 && *expr == ' ') expr++;
while (*expr != 0) {
if (*expr >= '0' && *expr <= '9')
result = result * 10 + *expr - '0';
else
return result;
expr++;
}
return result;
}
double eval(const char*& expr, int breakPrecedence = MAX_PRECEDENCE + 1);
// evalRight function reads the right part of an expression and evaluates it
// (up to the point where an operator with precedence 'breakPrecedence' is reached)
// returns the computation of the expression with the left operand passed as parameter.
double evalRight(const char*& expr, int breakPrecedence, double leftOperand)
{
do
{
auto posBeforeOp = expr;
auto op = readOperator(expr);
if (op == 0)
return leftOperand; // end of expression reached, meaning there is no right part
auto prec = precedenceOf(op);
if (prec >= breakPrecedence)
{
expr = posBeforeOp; // we backtrack before the operator (which will be handled by one of our caller)
return leftOperand;
}
// reads and evaluates the expression on the right hand side
auto rightOperand = eval(expr, prec);
// computes the current operation, the result becoming the new left operand of the next operation
leftOperand = computeOp(leftOperand, rightOperand, op);
} while (true);
}
// eval function reads an expression and evaluates it (evaluates it up to the point where an operator with precedence 'breakPrecedence' is reached)
// returns the evaluation of the expression
double eval(const char*& expr, int breakPrecedence)
{
auto leftOperand = readOperand(expr);
return evalRight(expr, breakPrecedence, leftOperand);
}
int main()
{
auto expression = "1 + 1 * 2 - 2 * 3 + 1";
std::cout << "result = " << eval(expression); // prints: result = -2
return 0;
}
To keep the code as simple as possible the provided expression is assumed to be syntactically correct. It's up to you to add some checks if you want.
Hope this helps.
As you said
I'd like to craft something of my own, this is not production-code. Just hobby.
so probably you want to learn a thing or two. That's why I won't write any code here and steal all the fun from you.
Looks like you should start from the basics. I could've recommend you the Dragon Book but you probably want to get your hands dirty right away instead of reading the classics for a week. So you can start with PEGs - it's really simple.
I've started to love parsing after I've read this article.
In your case the grammar will be quite simple:
Expr ← Sum
Sum ← Product (('+' / '-') Product)*
Product ← Value (('*' / '/') Value)*
Value ← [0-9]+
With functions you can rewrite it like this
value = repeat_at_least_once(character("0"),...,character("9"))
product = sequence(value , repeat(one_of(character("*"),character("/")), value )
expr = sequence(product, repeat(one_of(character("+"),character("-")), product)
All you have to do now - write these functions :) It will be not much longer than the code you've written, if not shorter.
If you fill confident, you can even implement packrat parsing with left recursion support, in this case you grammar will be even simpler.
IMHO, your current approach (doing multiplications and divisions first, then continuing with addition and subtraction, and all in one function) will be painful at best. Your calculate function is very hard to reason about already, because it mixes multiple cases already, e.g.
first pass or second pass (depending on the content of string action, which is the current status of the expression, which you modify from call to call)
first_nr empty/filled
second_nr empty/filled
Now imagine that more operators are added, like ^ and ( and ). I do understand that this is a hobby project. But even if you get this to work one day, you will not be able to understand it a week later.
Since you want to reuse your current code, how about this:
Think about how you yourself (as a human being) would go about this? There are multiple approaches. Independent of the specific algorithm they consist of two parts:
Tokenization (identifying numbers and operators)
Evaluation (combine those numbers and operators)
You are mixing both parts in your code. It would be much simpler for you and anybody you are asking for help if you separated them.
Tokenization is simple (you are doing it already, although I would recommend to treat the expression string as read-only).
Evaluation is more tricky, because you have to think about operator precedence. But again, it helps to think about how you would do it as a human. You might read from left to right. How do you handle that as a person? You might evaluate sub expressions with higher precedence first (as you intend to do now). How do you store the tokens? Think of different data structures. Lists, stacks, or queues for examples.
There are many ways. Once you found one, looking at some literature should be fun.
Enjoy!
While I clearly stated I did not want a postfix solution, I actually realized it's the most sane solution. I made a postfix solution myself with the help of tutorials (and still learnt a lot!). Thanks everyone for the help and suggestions.
#include <iostream>
#include <string>
#include <stack>
/*
* Function to check if a given character is an operator (+, -, *, /) or not
* :param c: Character to check
* :return bool: Returns true if parameter c is an operator
*/
bool isOperator(char c) {
char operators[4] = {'+', '-', '*', '/'};
if (std::find(std::begin(operators), std::end(operators), c) != std::end(operators)) {
return true;
}
return false;
}
/*
* Function to get the precedence matching the character
*
* :param a: Character containing the operator to get precedence from
* :return int: Integer representing precedence. Operators with high precedence (e.g * and /) return a higher value than e.g + and -.
*
* Example:
* precedence('*') > precedence('+') == true
*
*/
int precedence(char a) {
switch (a) {
case '+': return 1;
break;
case '-': return 1;
break;
case '*': return 2;
break;
case '/': return 2;
break;
}
return -1;
}
/*
* Function to convert an infix string to postfix notation
* :param infix: Infix string
* :return string: returns postfix string
*
* Example:
* std::string s = "5+5";
* toPostfix(s) == "5 5 +"
*
*/
std::string toPostfix(std::string& infix) {
std::string postfix = "";
//Stack to hold operators and nr is a helper string to
//group digits in numbers
std::stack<char> stack;
std::string nr = "";
//If first character is a minus-operator (AKA a negative number)
//add "0"
if (infix[0] == '-') {
infix = "0" + infix;
}
//Looping over infix string
for (int i = 0; i < infix.size(); i++) {
//If current evaluated character ain't an operator, it's a digit
if (!isOperator(infix[i])) {
//If digit is in a group of digits (AKA a number) put the whole number in nr
while (!isOperator(infix[i]) && i < infix.size()) {
nr += infix[i];
i++;
}
i--;
//Append the number to the postfix string
postfix += nr + " ";
nr = "";
} else {
//This block is executed when evaluated character is an operator
//If stack is empty, or the evaluated operator is higher than the one in the stack
//push it to the stack (Needs to be appended to the postfix string later)
if (stack.size() == 0 || precedence(infix[i]) > precedence(stack.top())) {
stack.push(infix[i]);
} else {
//While the stack contacts a higher or equally high precedence as currently
//evaluated operator
while (precedence(stack.top()) >= precedence(infix[i])) {
//We append the top of the stack to the postfix string
postfix += stack.top();
postfix += ' ';
stack.pop();
if (stack.size() == 0) {
break;
}
}
//Push evaluated operator to stack
stack.push(infix[i]);
}
}
}
//Append all remaining operators to the postfix string
while (stack.size() != 0) {
postfix += stack.top();
stack.pop();
}
return postfix;
}
/*
* Evaluate two numbers regaring the used operator
* :param x: First number to do evaluation with
* :param y: Second number to do evaluation with
* :param _operator: Operator to do calculation with
* :return double: Result of the evaluation
*
* Example:
* x: 5
* y: 60
* _operator: +
* = 65
*/
double evaluate(double x, double y, char _operator) {
switch(_operator) {
case '+':
return x + y;
break;
case '-':
return x - y;
break;
case '*':
return x * y;
break;
case '/':
return x / y;
break;
}
return 0;
}
/*
* Calculate the result of an infix string
* :param s: String containing the infix notation
* :return double: Result of the calculation
*
* Example:
* std::string s = "5+5";
* calculate(s) == 10
*/
double calculate(std::string& s) {
//Convert infix to postfix
s = toPostfix(s);
//Stack holding operators and nr (string) for separating numbers
std::stack<double> stack;
std::string nr = "";
//Looping over postfix string
for (int i = 0; i < s.size(); i++) {
if (s[i] == ' ') {
continue;
}
//If evaluated character is a digit,
//put it in nr
if (isdigit(s[i])) {
//If digit is first of a group of digits, put that group of digits
//AKA a number in nr
while (isdigit(s[i])) {
nr += s[i];
i++;
}
i--;
//Pushing nr in stack
stack.push(std::stod(nr));
nr = "";
} else {
//If current evaluated character is not a digit
//but an operator, do a calculation
//Retrieve first number for calculation
int x = stack.top();
stack.pop();
//Retrieve second number for calculation
int y = stack.top();
stack.pop();
//Put evaluation result in integer and push into stack
int result = evaluate(y, x, s[i]);
stack.push(result);
}
}
//Final number is in stack
return stack.top();
}
int main() {
std::string s = "-5*5-2*2+3-10/5";
std::cout << calculate(s) << std::endl;
}
you need divided calculation for several steps
copy expression to writable memory and check/normalize it:
.check that all chars valid (positive)
.remove spaces
.convert all to low (or upper) case (if case you use hex expressions)
.some operators take 2 symbols ( ==, !=, >=, <=, <<, >>, ||, && ) - replace it to single symbol, from not valid (negative) range
remove ( ) if exist - calculate expressions in ():
.find first ) symbol from begin
.find last ( before it.
.check that after ) and before ( was separator symbols (operator or begin/end of string) but not digit.
.format new string where you replace (..) with it digital result
remove (calculate) all unary operators (+, -, !, ~)
.unary operators - on right side must have digit and on left - another operator(or begin of string), but not digit
.format new string with result of unary operator
remove (calculate) all binary operators.
.we need calculate in reverse precedence - so first need calculate/remove operators with lowest precedence.
.so need do loop by operators (from low to high precedence) - search operator symbol in string.
.if found - A op B - calculate separate A and B and then apply op.
convert string to integer
.now, after all ( ) and operators removed - only digit must be in string
example of code:
namespace Eval
{
typedef INT_PTR (* fn_b_op)(INT_PTR a, INT_PTR b);
typedef INT_PTR (* fn_u_op)(INT_PTR a);
struct b_op_arr { fn_b_op pfn; char c; };
struct u_op_arr { fn_u_op pfn; char c; };
struct name_to_char { char b[3]; char c;};
static INT_PTR fn1_bnt(INT_PTR a){ return !a; }
static INT_PTR fn1_not(INT_PTR a){ return ~a; }
static INT_PTR fn1_add(INT_PTR a){ return +a; }
static INT_PTR fn1_sub(INT_PTR a){ return -a; }
static INT_PTR fn2Land(INT_PTR a,INT_PTR b){ return a && b; }
static INT_PTR fn2_Lor(INT_PTR a,INT_PTR b){ return a || b; }
static INT_PTR fn2_equ(INT_PTR a,INT_PTR b){ return a == b; }
static INT_PTR fn2_nqu(INT_PTR a,INT_PTR b){ return a != b; }
static INT_PTR fn2_lqu(INT_PTR a,INT_PTR b){ return a < b; }
static INT_PTR fn2_gqu(INT_PTR a,INT_PTR b){ return a > b; }
static INT_PTR fn2_leu(INT_PTR a,INT_PTR b){ return a <= b; }
static INT_PTR fn2_geu(INT_PTR a,INT_PTR b){ return a >= b; }
static INT_PTR fn2_add(INT_PTR a,INT_PTR b){ return a + b; }
static INT_PTR fn2_sub(INT_PTR a,INT_PTR b){ return a - b; }
static INT_PTR fn2_mul(INT_PTR a,INT_PTR b){ return a * b; }
static INT_PTR fn2_div(INT_PTR a,INT_PTR b){ return a / b; }
static INT_PTR fn2_dv2(INT_PTR a,INT_PTR b){ return a % b; }
static INT_PTR fn2_lsh(INT_PTR a,INT_PTR b){ return (UINT_PTR)a << b; }
static INT_PTR fn2_rsh(INT_PTR a,INT_PTR b){ return (UINT_PTR)a >> b; }
static INT_PTR fn2_xor(INT_PTR a,INT_PTR b){ return a ^ b; }
static INT_PTR fn2_and(INT_PTR a,INT_PTR b){ return a & b; }
static INT_PTR fn2__or(INT_PTR a,INT_PTR b){ return a | b; }
enum /*: char*/ { equ = -0x80, not_equ, less_equ, gre_equ, l_or, l_and, r_shift, l_shift };
inline static b_op_arr b_arr[] =
{
{fn2_mul, '*'}, {fn2_div, '/'}, {fn2_lsh, l_shift}, {fn2_rsh, r_shift},
{fn2_xor, '^'}, {fn2_dv2, '%'}, {fn2_and, '&'}, {fn2__or, '|'},
{fn2_equ, equ}, {fn2_nqu, not_equ}, {fn2_lqu, '<'}, {fn2_gqu, '>'},
{fn2_leu, less_equ},{fn2_geu, gre_equ},{fn2_add, '+'}, {fn2_sub, '-'},
{fn2Land, l_and}, {fn2_Lor, l_or}
};
inline static u_op_arr u_arr[] =
{
{fn1_add, '+'}, {fn1_sub, '-'}, {fn1_bnt,'!'}, {fn1_not,'~'}
};
inline static name_to_char _2_to_1[] =
{
{"==", equ}, {"!=", not_equ}, {"<=", less_equ}, {">=", gre_equ },
{">>", r_shift}, {"<<", l_shift}, {"||", l_or}, {"&&", l_and},
};
void initBits(LONG bits[], const char cc[], ULONG n)
{
do
{
_bittestandset(bits, cc[--n]);
} while (n);
}
static bool IsSeparatorSymbol(char c)
{
static LONG bits[8];
static bool bInit;
if (!bInit)
{
// acquire
static const char cc[] = {
'*', '/', '+', '-', '^', '%', '&', '|', '<', '>', '!', '~', '(', ')',
equ, not_equ, less_equ, gre_equ, l_or, l_and, r_shift, l_shift, 0
};
initBits(bits, cc, _countof(cc));
// release
bInit = true;
}
return _bittest(bits, c);
}
static bool IsUnaryOpSymbol(char c)
{
static LONG bits[8];
static bool bInit;
if (!bInit)
{
// acquire
static char cc[] = {
'+', '-', '!', '~'
};
initBits(bits, cc, _countof(cc));
// release
bInit = true;
}
return _bittest(bits, c);
}
static bool IsDigit(char c)
{
static LONG bits[8];
static bool bInit;
if (!bInit)
{
// acquire
static char cc[] = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
};
initBits(bits, cc, _countof(cc));
// release
bInit = true;
}
return _bittest(bits, c);
}
__int64 strtol64_16(char* sz, char** psz)
{
__int64 r = 0;
while (char c = *sz)
{
ULONG d;
if ((ULONG)(c - '0') <= '9' - '0')
{
d = (c - '0');
}
else if ((ULONG)(c - 'a') <= 'z' - 'a')
{
d = (c - 'a') + 10;
}
else
{
break;
}
r = (r << 4) + d;
sz++;
}
*psz = sz;
return r;
}
bool Normalize(const char* psz, char* buf, size_t s)
{
int len = 0;
do
{
--s;
char c = *psz++, d;
// is valid char
if (c < 0) return false;
// skip space
if (c == ' ') continue;
if ((ULONG)(c - 'A') < (ULONG)('Z' - 'A'))
{
c += 'a' - 'A';
}
// not last char
if (s)
{
d = *psz;
int k = _countof(_2_to_1);
do
{
if (_2_to_1[--k].b[0] == c && _2_to_1[k].b[1] == d)
{
c = _2_to_1[k].c, psz++, --s;
break;
}
} while (k);
}
*buf++ = c, len++;
} while (s);
return 0 < len;
}
char* format_new_str(const char* a, INT_PTR r, const char* b)
{
static const char format[] = "%s%I64x%s";
int len = _scprintf(format, a, r, b);
if (0 < len)
{
if (char* buf = new char [++len])
{
if (0 < sprintf_s(buf, len, format, a, r, b))
{
DbgPrint("++%p\n\"%s\"\n", buf, buf);
return buf;
}
delete buf;
}
}
return 0;
}
bool _calc (char* str, INT_PTR& result)
{
DbgPrint("\"%s\"\n", str);
struct SB
{
char* str;
SB() : str(0) {}
~SB()
{
operator <<(0);
}
void operator <<(char* psz)
{
if (str)
{
DbgPrint("--%p\n", str);
delete [] str;
}
str = psz;
}
} sb;
size_t len = strlen(str);
if (!len)
{
return false;
}
char b, c;
int l;
INT_PTR r, q;
//1. remove ( )
char *psz = str, *pc = 0, *buf;
for (;;)
{
switch (*psz++)
{
case '(':
pc = psz;
continue;
case ')':
if (!pc || !IsSeparatorSymbol(*psz) || (pc > str + 1 && !IsSeparatorSymbol(pc[-2]))) return false;
psz[-1] = 0, pc[-1] = 0;
if (_calc(pc, r) && (buf = format_new_str(str, r, psz)))
{
sb << buf;
psz = str = buf, pc = 0;
continue;
}
return false;
case 0:
goto __2;
}
}
__2:
//2. remove unary op
psz = str;
do
{
if (IsDigit(c = *psz) && str < psz && IsUnaryOpSymbol(c = psz[-1]) && (psz == str + 1 || IsSeparatorSymbol(psz[-2])))
{
psz[-1] = 0;
l = _countof(u_arr);
do
{
if (u_arr[--l].c == c)
{
r = strtol64_16(psz, &psz);
if (IsSeparatorSymbol(*psz))
{
r = u_arr[l].pfn(r);
if (buf = format_new_str(str, r, psz))
{
sb << buf;
psz = str = buf;
goto __2;
}
}
break;
}
} while (l);
return false;
}
} while (psz++, c);
//3. remove binary op
l = _countof(b_arr);
do
{
c = b_arr[--l].c;
psz = str;
do
{
if (c == (b = *psz++))
{
psz[-1] = 0;
if (_calc(psz, q) && _calc(str, r))
{
result = b_arr[l].pfn(r, q);
return true;
}
return false;
}
} while (b);
} while (l);
result = strtol64_16(str, &str);
return !*str;
}
bool calc(const char* psz, INT_PTR& result)
{
bool fOk = false;
if (size_t s = strlen(psz))
{
if (char* buf = new char[++s])
{
if (Normalize(psz, buf, s))
{
fOk = _calc(buf, result);
}
delete [] buf;
}
}
return fOk;
}
};
use
INT_PTR r;
Eval::calc(str, r);
While reading Learning Go I've implemented some of the suggested training programs. One of which has nearly the same requirements as yours, although I have to admit, that yours is a bit more evolved. So, I hope you can get something out of this code (I know it's not C++, but I'm sure you can read it):
package main
import (
"fmt"
"os"
"bufio"
"stack"
"strconv"
)
func readInput() string {
reader := bufio.NewReader(os.Stdin)
switch in, ok := reader.ReadString('\n'); true {
case ok != nil:
fmt.Printf("Failed to read inputs: %v", ok)
return "error"
default:
return in[:len(in)-1]
}
}
func isdigit(in string) bool {
_,ok := strconv.Atoi(in)
return ok == nil
}
func isOperation(in string) bool {
chars := []rune(in)
return '+' == chars[0] || '-' == chars[0] || '*' == chars[0] || '/' == chars[0]
}
func calc(operation string, op2, op1 int) float32 {
chars := []rune(operation)
switch chars[0] {
case '+':
return float32(op1 + op2)
case '-':
return float32(op1 - op2)
case '*':
return float32(op1 * op2)
case '/':
return float32(op1) / float32(op2)
}
print("Failed to recognize operation: ")
println(operation)
fmt.Printf("%v\n", chars)
return 0.0
}
func main() {
var st stack.Stack
fmt.Println("Calculator.")
fmt.Println("Please input operations and then one of + - * / for calculation,")
fmt.Println("or anything else for exit.")
LOOP: for {
in := readInput()
switch {
case isdigit(in):
i,_ := strconv.Atoi(in)
st.Push(i)
case isOperation(in):
op2 := st.Pop()
op1 := st.Pop()
res := calc(in, op2, op1)
st.Push(int(res))
fmt.Println(res)
default:
fmt.Println("Exit")
break LOOP
}
}
}
... similar, isn't it?

How can I make a char a= ‘+’(or string[]) into a real operation?

Ex:5 a 5 = 10. I am trying to do a linear equation calculator and I am beginning with an string. I can convert it to numbers but not make the chat equivalent to the + sign ( for example) actually do what a + sign does...
In c-style languages, code is compiled before it can be run, so you can't just directly run a string as if it were code at runtime. However, you could build a rudimentary interpreter do accomplish your task. For example:
if (op == '+') {
result = a + b;
} else if (op == '-') {
result = a - b;
}
I think you can convert the characters in the string to something that provide more information.
I have wrote an example (very simple) that handle characters from A-Z and a-z as variables, 0-9 as constants, and the standard operators '+', '-', '*' and '/'.
It handles only integers problems and few operators but it is just a simple example only meant to illustrate my idea.
Code
tools.h
#ifndef TOOLS_H
#define TOOLS_H
#include <vector>
#include <string>
namespace interp
{
enum class ITEM_TYPE {OPERATOR, OPERAND};
enum class VAR_TYPE {CONSTANT, VARIABLE};
enum class SOLVE_STATUS{SUCCESS, FAILED};
const int solve_init_value = 0; // Value used for initializing variables for the solve algorithm
struct Item
{
ITEM_TYPE item_t;
Item(ITEM_TYPE t);
};
struct Operator : public Item
{
char op;
Operator(char o);
int operate(int a, int b);
};
struct Operand : public Item
{
VAR_TYPE var_t;
int value;
Operand(VAR_TYPE t, int v);
};
std::vector<std::string> split(const std::string & s, char c);
Item * convert(char c);
SOLVE_STATUS solve(std::vector<Item*> lhs, std::vector<Item*> rhs);
}
#endif // TOOLS_H
tools.cpp
#include "tools.h"
namespace interp
{
Item::Item(ITEM_TYPE t) : item_t(t)
{}
// ---------- ---------- ---------- ---------- ----------
Operator::Operator(char o) : Item(ITEM_TYPE::OPERATOR), op(o)
{}
int Operator::operate(int a, int b)
{
int res;
switch(op)
{
case '+': res = a+b; break;
case '-': res = a-b; break;
case '*': res = a*b; break;
case '/': res = a/b; break;
default: /* Do what you want */ throw std::string("Unknown Operator");
}
return res;
}
// ---------- ---------- ---------- ---------- ----------
Operand::Operand(VAR_TYPE t, int v) : Item (ITEM_TYPE::OPERAND), var_t(t), value(v)
{}
// ---------- ---------- ---------- ---------- ----------
std::vector<std::string> split(const std::string & s, char c)
{
std::vector<std::string> splitted;
std::string word;
for(char ch : s)
{
if((ch == c) && (!word.empty()))
{
splitted.push_back(word);
word.clear();
}
else
word += ch;
}
if(!word.empty())
splitted.push_back(word);
return splitted;
}
// ---------- ---------- ---------- ---------- ----------
Item * convert(char c)
{
if((c < 48) || (c > 126)) // check for invalid characters
return nullptr;
if((c >= 48) && (c <= 57)) // constant integer values (0 to 9)
return new Operand(VAR_TYPE::CONSTANT, static_cast<int>(c));
if((c >= 65) && (c <= 90)) // variable integer values (char A-Z)
return new Operand(VAR_TYPE::VARIABLE, solve_init_value);
if((c >= 97) && (c <= 122)) // variable integer values (char a-z)
return new Operand(VAR_TYPE::VARIABLE, solve_init_value);
return new Operator(c);
}
}
main.cpp
#include "tools.h"
#include <iostream>
int main()
{
std::string equation("1+x=5*3");
std::vector<std::string> separatedSides(interp::split(equation, '='));
if(separatedSides.size() != 2)
{
std::cout << "Error: Too many '=' found in the string." << std::endl;
return -1;
}
std::vector<interp::Item *> leftHandSide;
std::vector<interp::Item *> rightHandSide;
// Convert the left hand side
for(char c : separatedSides[0])
{
interp::Item * item(interp::convert(c));
if(item != nullptr)
leftHandSide.push_back(item);
else
{
std::cout << "Error: Unknown character encountered." << std::endl;
return -1;
}
}
// Convert the right hand side
for(char c : separatedSides[1])
{
interp::Item * item(interp::convert(c));
if(item != nullptr)
rightHandSide.push_back(interp::convert(c));
else
{
std::cout << "Error: Unknown character encountered." << std::endl;
return -1;
}
}
// Now you can solve the problem knowing what Item is.
interp::SOLVE_STATUS status = interp::solve(leftHandSide, rightHandSide);
// Release memory at the end
for(interp::Item * item : leftHandSide)
delete item;
for(interp::Item * item : rightHandSide)
delete item;
leftHandSide.clear();
rightHandSide.clear();
return 0;
}
Explanation
I didn't write the solve method (just written in the header but not implemented), this is more your job than mine :)
But, with that Item formulation of characters, you can easily identify what is what (Operand (constant or variable) or Operator).
In Operator items, you have the method operate() that can perform the operation for you, so that in your solve() function, you just have to call this function and check that no error happened (for unknown operators for example).
So you can adapt this code to your case, in order to handle more complex cases, for example the ( and ) for the priority rules, double values instead of just integers (.), ...
Perhaps the code needs some adjustments but this is not my point.
I hope it can help.

Graphs in C++ Using Adjacency Matrix and List

I am currently working on a small assignment using Graphs to display characters in an adjacency list. Normally our professor supplies us with examples from class that he works out, however he has not given us any examples this time. This is just a one point extra credit assignment but the real reason I am seeking help is the fact that we have a 50 point in class assignment Friday. Me nor my other classmates know what is going on currently. This is the function that I cannot get.
My main question is how would I convert the string * value returned by the
split function to use in a call to the markEdge function?
void loadListFromFile(Graph& g, string filename) {
/* TODO (1):
*
* Open the file and update the matrix with the proper
* edge status, i.e. 1 if there is an edge from source
* to target.
*
* The file format is:
*
* sourceNode adjacentNode1 adjacentNode2 ...adjacentNode3
*
* Each node is a single character in the range A-Z.
*/
ifstream ifs;
ifs.open(filename);
if (ifs.is_open() == false){
cerr << "Error opening file for reading." << endl;
}
string line;
int tokenCount;
getline( ifs, line);
while (!ifs.eof()){
split(line, ' ', tokenCount);
getline(ifs, line);
}
}// end loadListFromFile()
Here is a given function used to split the values
//given
string * split(const string& str, const char delimiter, int& tokenCount){
string * fields = nullptr;
tokenCount = 0;
string token;
string remaining = str;
if (remaining.back() == '\n') {
remaining.pop_back();
}
remaining.push_back(delimiter);
size_t delimiterPos = remaining.find_first_of(delimiter, 0);
while ( delimiterPos != string::npos ) {
token = remaining.substr(0, delimiterPos);
remaining = remaining.substr(delimiterPos + 1);
if ( fields ) {
// resize array and add new token.
string * fieldsTmp = new string [tokenCount + 1];
for (int i = 0; i <= tokenCount - 1; i++) {
fieldsTmp[i] = fields[i];
}
fieldsTmp[tokenCount++] = token;
delete [] fields;
fields = fieldsTmp;
fieldsTmp = nullptr;
} else {
// create array and add first token.
fields = new string[tokenCount + 1];
fields[tokenCount++] = token;
}
delimiterPos = remaining.find_first_of(delimiter, 0);
}
return fields;
}// end split()
Here is a function that I believe is right.
void markEdge(const int fromIndex, const char node) {
/* TODO (1):
* Add the node to the list at index fromIndex.
*/
adjList->pushAt(fromIndex, node);
}// end markEdge()
Thanks for the help.

I keep encountering the error " Error: Syntax error, insert "}" to complete ClassBody"

I know there are other errors present but the main one is the bracket that is supposed to close my main method. It ask me to enter another bracket to close the class body. I have gone through many times, correctly indenting and entering in brackets to close loops and methods but it just doesn't want to work. Any ideas?
import java.util.Stack;
import java.util.Scanner;
public class RPNApp{
public static void main (String [] args)
{
/* Scanner object which takes user input and splits each element into an array of type String*/
Scanner scan = new Scanner(System.in);
System.out.println("Please enter numbers and operators for the Reverse Polish Notation calculator.");
String scanner = scan.nextLine();
String [ ] userInput = scanner.split(" ");
Stack<Long> stack = new Stack<Long>();
for (int i = 0; i <= userInput.length; i++) {
if (isNumber()) {
Long.parseLong(userInput[i]);
stack.push(Long.parseLong(userInput[i]));
}
}
}
public static boolean isOperator (String userInput[i]) //userInput is the array.
{
for (int i = 0; i<userInput.length; i++) {
if (!(x.equals("*") || x.equals("+") || x.equals("-") || x.equals("/") || x.equals("%"))) {
return false;
}else {
return true;
}
}
}
public static boolean isNumber (String userInput[i])
{
for (int i = 0; i<x.length(); i++) {
char c = x.charAt(i);
if (!(Character.isDigit(c))) {
return false;
}
} return true;
}
}
I have made quite a few changes, I knew there were other errors present. But the error I encountered from not having a correct parameter in my method was the worry. You mentioned there was still something wrong, have I tended to the syntax error you noticed?
Updated code
import java.util.Stack;
import java.util.Scanner;
public class RPNApp{
public static void main (String [] args){
/* Scanner object which takes user input and splits each element into an array of type String*/
Scanner scan = new Scanner(System.in);
System.out.println("Please enter numbers and operators for the Reverse Polish Notation calculator.");
String scanner = scan.nextLine();
String [ ] userInput = scanner.split(" ");
Stack<Long> stack = new Stack<Long>();
for (int i = 0; i < userInput.length; i++) {
String current = userInput[i];
if (isNumber(current)) {
Long.parseLong(userInput[i]);
stack.push(Long.parseLong(userInput[i]));
System.out.println(stack.toString());
}
}
}
public static boolean isOperator (String x) { //userInput is the array.
if (!(x.equals("*") || x.equals("+") || x.equals("-") || x.equals("/") || x.equals("%"))) {
return false;
}else {
return true;
}
}
public static boolean isNumber (String x) {
for (int i = 0; i<x.length(); i++) {
char c = x.charAt(i);
if (!(Character.isDigit(c))) {
return false;
}
} return true;
}
}
This piece of code certainly has more than just a few issues. But if you have written it entirely in your head without ever compiling it, it's actually pretty good! It shows that you think about the problem in a surprisingly correct way. I don't understand how one can get so many details wrong, but the overall structure right. And some of the syntax errors aren't really your fault: it's absolutely not obvious why it should be array.length but string.length() but at the same time arrayList.size(), it's completely inconsistent mess.
Here, I cleaned it up a bit:
import java.util.Stack;
import java.util.Scanner;
public class RPNApp {
public static void main(String[] args) {
/* Scanner object which takes user input and splits each element into an array of type String*/
Scanner scan = new Scanner(System. in );
System.out.println("Please enter numbers and operators for the Reverse Polish Notation calculator.");
String scanner = scan.nextLine();
String[] userInput = scanner.split(" ");
Stack<Long> stack = new Stack<Long>();
for (int i = 0; i <= userInput.length; i++) {
if (isNumber(userInput[i])) {
Long.parseLong(userInput[i]);
stack.push(Long.parseLong(userInput[i]));
}
}
}
public static boolean isOperator(String userInput) {
for (int i = 0; i < userInput.length(); i++) {
char x = userInput.charAt(i);
if (!(x == '*' || x == '+' || x == '-' || x == '/' || x == '%')) {
return false;
}
}
return true;
}
public static boolean isNumber(String s) {
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (!(Character.isDigit(c))) {
return false;
}
}
return true;
}
}
Few other points to notice:
Exists-loops: Check if true, return true in loop, return false in the end.
Forall-loops: Check if false, return false in loop, return true in the end.
Chars and Strings are not the same. Chars are enclosed in single quotes and compared by ==.
It's still wrong. Think harder why. And try not to post non-compilable stuff any more.
In your function parameters you can't have userInput[i] like that. Get rid of the [i] part and then fix the rest of the other errors.