5 Replies Latest reply: Dec 5, 2010 9:35 AM by YoungWinston RSS

    Java assignment.

    821200
      can anyone help me with this.., i want to output something like this.
      sample:
      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..
      i think i need AST to output the entire (transformed) tree after every evaluation step.
      i really need help., my lecturer gave us a deadline for this. T_T


      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;
      }
      }


      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;
      }

      }
        • 1. Re: Java assignment.
          DarrylBurke
          Moderator advice: Please read the announcement(s) at the top of the forum listings and the FAQ linked from every page. They are there for a purpose.

          Then edit your post and format the code correctly.

          db
          • 2. Re: Java assignment.
            DarrylBurke
            Cross posted
            http://www.java-forums.org/new-java/35617-java-assignment.html

            db
            • 3. Re: Java assignment.
              821200
              it me too..at java forums that org
              • 4. Re: Java assignment.
                821200
                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;
                } 
                } 
                
                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;
                } 
                
                }
                its my first time to post here..,
                • 5. Re: Java assignment.
                  YoungWinston
                  user13418429 wrote:
                  can anyone help me with this.., i want to output something like this.
                  sample:
                  40 + 10 - 20 / 10
                  40 + 10 - 10
                  50 - 10
                  40
                  Then you need an expression parser...and they aren't trivial.

                  For example:
                  How does it know that '20 / 10' needs to be evaluated first? (That is correct, BTW)
                  Why is it '50 - 10', and not '40 + 0'?
                  i really need help., my lecturer gave us a deadline for this. T_T
                  [url http://www.catb.org/~esr/faqs/smart-questions.html#urgent]your problem; not ours.

                  My advice: Stop. Take a deep breath, and write down in English (or your native language) how your parser is supposed to work. When you are sure you understand it, then start coding.

                  Winston

                  Edited by: YoungWinston on Dec 5, 2010 4:20 PM

                  You may also want to Google 'Reverse Polish Notation' and 'RPN translation'. If you can get to RPN, you may find the whole printing out business a lot easier.