1. Member
Join Date
Dec 2010
Posts
7
Rep Power
0

## Java assignment.

We were ask to do this.
the use will input any operations or math problem following MDAS.
Sample:

Input:
40 + 10 - 20 / 5 * 2

and the output should be in passes.

Output:
40 + 10 - 20 / 10
40 + 10 - 10
50 - 10
40

is it possible to do this?? im really new to java., and i really need help :confused::confused:

2. Senior Member
Join Date
Jun 2008
Posts
2,568
Rep Power
15
Originally Posted by jmsjames
is it possible to do this??
Of course. And your lectures up to this point will have pointed out techniques to do so. You did take notes, right?
im really new to java., and i really need help :confused::confused:
Well, let's see your code and hear a specific question and we'll be glad to help, but it sounds like you want a cut-n-paste answer for your homework and that we're not going to do.

3. So it has to be input? or do you set the formula up? (just so you know i'm fairly new myself, i'm just taking an online coruse through my high school at the moment, and i'm up to constructers and methods at the moment.)

4. Member
Join Date
Dec 2010
Posts
7
Rep Power
0
wait., we just finished studying some types of sorting, i dont even know if its related to the problem, and our lecturer is not that good.., i just want to know how can i use the users input which is a string and change it to logical operations and shows its output..,

5. Member
Join Date
Dec 2010
Posts
7
Rep Power
0
Originally Posted by Darkflame
So it has to be input? or do you set the formula up? (just so you know i'm fairly new myself, i'm just taking an online coruse through my high school at the moment, and i'm up to constructers and methods at the moment.)
it has to be inputted by the user. thats why i dont how to manipulate it..it follows MDAS (* / + -)

6. Oh okay, sorry then I can't really help, strings is two units away, next is applicates and animation then strings

7. Senior Member
Join Date
Jun 2008
Posts
2,568
Rep Power
15
Yeah, yeah. There are no good lecturers and the assignment never has anything to do with the lectures, if we were to listen to all the posters on these sites.

Even if that is true, that does not exempt you from at least making an attempt.

8. Originally Posted by jmsjames
wait., we just finished studying some types of sorting, i dont even know if its related to the problem, and our lecturer is not that good.., i just want to know how can i use the users input which is a string and change it to logical operations and shows its output..,
Of course, all teachers are crap; you can either pass your expression in String form to a script interpreter (such as the bundled Javascript engine) but you want step by step output so you have to craft your own parser. A simple recursive descent parser can do the job. The parser has to generate some form of AST (Abstract Syntax Tree) and output the entire (transformed) tree after every evaluation step.

All other methods are doomed to fail.

kind regards,

Jos

9. Member
Join Date
Dec 2010
Posts
7
Rep Power
0

## my prog

Originally Posted by JosAH
A simple recursive descent parser can do the job. The parser has to generate some form of AST (Abstract Syntax Tree) and output the entire (transformed) tree after every evaluation step.

Jos
ii undersrtand now how to use recursive parser but i dont know how to put AST on it..,
i want this kind of output :
40 + 10 - 20 / 10
40 + 10 - 10
50 - 10
40
but now all i get is the answer.., can you check this one., its sloppy tho..

Java Code:
```import java.io.*;

public class Test {

public static void main(String args[]) {
Parser parser = new Parser(new Scanner(
new DataInputStream(System.in)));
System.out.print("Enter problem:");
parser.run( );
System.out.println("done");
}

}

class Token {

public static final int semicolon = 0;
public static final int period    = 1;
public static final int plusop    = 2;
public static final int minusop   = 3;
public static final int timesop   = 4;
public static final int divideop  = 5;
public static final int assignop  = 6;
public static final int lparen    = 7;
public static final int rparen    = 8;
public static final int letter    = 9;
public static final int number    = 10;

private static String[] spelling = {
";", ".", "+", "-", "*", "/", "=", "(", ")",
"letter", "number"};

public static String toString (int i) {
if (i < 0 || i > number)
return "";
return spelling[i];
}
}

class Scanner {
private char ch = ' ';
private char ident = ' ';
private int intValue = 0;
private Buffer buffer;
public int token;

public Scanner (DataInputStream in) {
buffer = new Buffer(in);
token = Token.semicolon;
}

public int getToken ( ) {
while (Character.isWhitespace(ch))
ch = buffer.get( );
if (Character.isLetter(ch)) {
ident = Character.toLowerCase(ch);
ch = buffer.get( );
token = Token.letter;
}
else if (Character.isDigit(ch)) {
intValue = getNumber( );
token = Token.number;
}
else {
switch (ch) {
case ';': ch = buffer.get( );
token = Token.semicolon;
break;

case '.': ch = buffer.get( );
token = Token.period;
break;

case '+': ch = buffer.get( );
token = Token.plusop;
break;

case '-': ch = buffer.get( );
token = Token.minusop;
break;

case '*': ch = buffer.get( );
token = Token.timesop;
break;

case '/': ch = buffer.get( );
token = Token.divideop;
break;

case '=': ch = buffer.get( );
token = Token.assignop;
break;

case '(': ch = buffer.get( );
token = Token.lparen;
break;

case ')': ch = buffer.get( );
token = Token.rparen;
break;

default: error ("Illegal character " + ch );
break;
}
}
}

public int number ( ) {
return intValue;
}

public char letter ( ) {
return ident;
}

public void match (int which) {
token = getToken( );
if (token != which) {
error("Invalid token " + Token.toString(token) +
"-- expecting " + Token.toString(which));
System.exit(1);
}
}

public void error (String msg) {
System.err.println(msg);
System.exit(1);
}

private int getNumber ( ) {
int rslt = 0;
do {
rslt = rslt * 10 + Character.digit(ch, 10);
ch = buffer.get( );
} while (Character.isDigit(ch));
return rslt;
}

}

class Buffer {
private String line = "";
private int column = 0;
private int lineNo = 0;
private DataInputStream  in;

public Buffer (DataInputStream in) {
this.in = in;
}

public char get ( ) {
column++;
if (column >= line.length()) {
try {
} catch (Exception e) {
System.exit(1);
}
if (line == null)
System.exit(0);
column = 0;
lineNo++;
System.out.println(line);
line = line + "\n";
}
return line.charAt(column);
}

}

class Parser {

private Scanner scanner;

public Parser(Scanner scanner) {
this.scanner = scanner;
}

public void run ( ) {
scanner.getToken( );
statement( );
}

private void statement ( ) {
while(scanner.token!= Token.period) {
int value = expression( );
System.out.println("=> " + value);
scanner.getToken( );  // flush ";"
}
}

private int expression ( ) {
int left = term( );
while (scanner.token == Token.plusop ||
scanner.token == Token.minusop) {
int saveToken = scanner.token;
scanner.getToken( );
switch (saveToken) {
case Token.plusop:
left += term( );
break;
case Token.minusop:
left -= term( );
break;
}
}
return left;
}

private int term ( ) {
int left = factor( );
while (scanner.token == Token.timesop ||
scanner.token == Token.divideop) {
int saveToken = scanner.token;
scanner.getToken( );
switch (saveToken) {
case Token.timesop:
left *= factor( );
break;
case Token.divideop:
left /= factor( );
break;
}
}
return left;
}

private int factor ( ) {
int value = 0;
switch (scanner.token) {
case Token.number:
value = scanner.number( );
scanner.getToken( );
break;
case Token.lparen:
scanner.getToken( );
value = expression( );
if (scanner.token!= Token.rparen)
scanner.error("Missing ')'");
scanner.getToken( );
break;
default:
scanner.error("Expecting number or (");
break;
}
return value;
}

}```
Last edited by Fubarable; 12-05-2010 at 04:09 AM. Reason: Moderator edit: code tags added, quote tags fixed

10. Member
Join Date
Dec 2010
Posts
7
Rep Power
0
Originally Posted by Darryl.Burke
Cross posted

db
thats me too lol..,

11. Originally Posted by jmsjames
thats me too lol..,
Yup, that's the idea. When cross-posting on other forums, please notify both us and the other forum of all posts of the same content, so that we don't waste our time answering a question that was already answered. ;)

12. Member
Join Date
Dec 2010
Posts
7
Rep Power
0
Originally Posted by Zack
Yup, that's the idea. When cross-posting on other forums, please notify both us and the other forum of all posts of the same content, so that we don't waste our time answering a question that was already answered. ;)
ok i get it.., i will tell if its answered.., im really sorry i just really wanna know the answer to my post., i will inform both forums.,.

13. Originally Posted by jmsjames
ii undersrtand now how to use recursive parser but i dont know how to put AST on it..,
i want this kind of output :
40 + 10 - 20 / 10
40 + 10 - 10
50 - 10
40
but now all i get is the answer.., can you check this one., its sloppy tho..
First of all: well done, parsing isn't a trivial matter. You are evaluating your expression(s) while you parse; you shouldn't do that, you should create your AST (Abstract Syntax Tree) while you parse. As I can see now you only need two type of nodes for an expression, a, say, BinOpNode for the binary operator expressions and a ValueNode for the literal values of the expression.

I'll do part of it, here's your expression() method again in terms of Node building:

Java Code:
```	private Node expression() {
Node left = term();
while (scanner.token == Token.plusop || scanner.token == Token.minusop) {
int saveToken = scanner.token;
scanner.getToken();
switch (saveToken) {
case Token.plusop:
left= new BinOpNode('+', left, term());
break;
case Token.minusop:
left= new BinOpNode('-', left, term());
break;
}
}
return left;
}```
Node itself can be an interface while the BinOpNode implements it. The BinOpNode looks something like this:

Java Code:
```public class BinOpNode implements Node {
private char operator;
private Node left;
private Node right;

public BinOpNode(char operator, Node left, Node right) {
this.operator= operator;
this.left= left;
this.right= right;
}

public char getOperator() { return operator; }
public Node getLeft() { return left; }
public Node getRight() { return right; }

public String toString() { return left+operator+right; }
}```
And the ValueNode is simply this:

Java Code:
```public class ValueNode implements Node {
private int value;
public ValueNode(int value) {
this.value= value;
}

public int getValue() { return value; }

public String toString() { return ""+value; }
}```
While strictly speaking you don't need it for evaluating the expression, the following Node type may come in handy:

Java Code:
```public class ParenthesesNode implements Node {
private Node value;
public ParenthesesNode(Node value) {
this.value= value;
}

public int getValue() { return value; }

public String toString() { return "("+value+"); }
}```
After the parse is done you have a tree of Nodes, your AST; now you have the choice of something else evaluating the tree or have the tree evaluate itself; when a node is evaluated it replaces itself with an 'evaluated form', e.g. a node (+, 3, 4) (a BinOpNode) replaces itself by a ValueNode (7); after every replacement you should print the entire tree (which is easy, simply print the tree, the recursive toString() method takes care of the rest.

I think you can take it from here.

kind regards,

Jos

14. Member
Join Date
Dec 2010
Posts
7
Rep Power
0
Originally Posted by JosAH
First of all: well done, parsing isn't a trivial matter.
I think you can take it from here.

kind regards,

Jos
thank you very much.., i almost thought that no one will answer it.,.
im working on it now. thanks again:)

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•