Results 1 to 15 of 15
  1. #1
    jmsjames is offline Member
    Join Date
    Dec 2010
    Posts
    7
    Rep Power
    0

    Default 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. #2
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    8

    Default

    Quote Originally Posted by jmsjames View Post
    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. #3
    Darkflame's Avatar
    Darkflame is offline Member
    Join Date
    Dec 2010
    Posts
    2
    Rep Power
    0

    Default

    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. #4
    jmsjames is offline Member
    Join Date
    Dec 2010
    Posts
    7
    Rep Power
    0

    Default

    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. #5
    jmsjames is offline Member
    Join Date
    Dec 2010
    Posts
    7
    Rep Power
    0

    Default

    Quote Originally Posted by Darkflame View Post
    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. #6
    Darkflame's Avatar
    Darkflame is offline Member
    Join Date
    Dec 2010
    Posts
    2
    Rep Power
    0

    Default

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

  7. #7
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    8

    Default

    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. #8
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,005
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by jmsjames View Post
    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
    cenosillicaphobia: the fear for an empty beer glass

  9. #9
    jmsjames is offline Member
    Join Date
    Dec 2010
    Posts
    7
    Rep Power
    0

    Default my prog

    Quote Originally Posted by JosAH View Post
    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;
    		}
    	    } 
    	    return token;
    	} 
    
    
    	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 {
    		    line = in.readLine( );
    		} catch (Exception e) {
    		    System.err.println("Invalid read operation");
    		    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 03:09 AM. Reason: Moderator edit: code tags added, quote tags fixed

  10. #10
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,189
    Rep Power
    19

  11. #11
    jmsjames is offline Member
    Join Date
    Dec 2010
    Posts
    7
    Rep Power
    0

    Default

    Quote Originally Posted by Darryl.Burke View Post
    Cross posted

    db
    thats me too lol..,

  12. #12
    Zack's Avatar
    Zack is offline Senior Member
    Join Date
    Jun 2010
    Location
    Destiny Islands
    Posts
    692
    Rep Power
    4

    Default

    Quote Originally Posted by jmsjames View Post
    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. ;)

  13. #13
    jmsjames is offline Member
    Join Date
    Dec 2010
    Posts
    7
    Rep Power
    0

    Default

    Quote Originally Posted by Zack View Post
    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.,.

  14. #14
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,005
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by jmsjames View Post
    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
    cenosillicaphobia: the fear for an empty beer glass

  15. #15
    jmsjames is offline Member
    Join Date
    Dec 2010
    Posts
    7
    Rep Power
    0

    Default

    Quote Originally Posted by JosAH View Post
    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:)

Similar Threads

  1. Help me please (Java assignment)
    By cris_carriaga in forum Java Applets
    Replies: 4
    Last Post: 10-06-2010, 04:11 PM
  2. My java assignment -- please help me !
    By java_beginner1 in forum New To Java
    Replies: 11
    Last Post: 05-20-2010, 04:00 PM
  3. Java assignment
    By xtianah77 in forum New To Java
    Replies: 1
    Last Post: 02-17-2008, 11:54 PM
  4. java assignment, need help bad.
    By carlos123 in forum New To Java
    Replies: 1
    Last Post: 11-06-2007, 04:53 PM
  5. Help with my assignment java
    By toby in forum New To Java
    Replies: 1
    Last Post: 08-07-2007, 05:59 AM

Posting Permissions

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