Solved

How to access method within the same class in C#

Posted on 2012-03-20
58
642 Views
Last Modified: 2013-12-16
Hi all,
How can i call other method within the same class? Because when i check through it seems like it didn't go to the toString()/toStringIndented() method after the constructor is called so is not printing out anything?

Can anyone show me how should i do so that i can call the another method and print it out?

public class CProgram
    {
        List<Declaration> decpart = new List<Declaration>();
        List<Statement> body = new List<Statement>();

        public CProgram(List<Declaration> d, List<Statement> b)
        {
            decpart = d;
            body = b;
        }

        public String toString()
        {
            return toStringIndented("");
        }
        public String toStringIndented(String indent)
        {
            string result = indent + "Program(\n";
            foreach(var item in decpart)
                result = result + item.toStringIndented(indent + "  ")  + ",\n";
            foreach(var item in body)
                result = result + item.toStringIndented(indent + "  ")  + ",\n";
            Console.WriteLine(result + indent + ")");
            return result  + indent + ")";
        }
    }

Open in new window


public CProgram program()
        {
            match(Token.TokenType.Int);
            match(Token.TokenType.Main);
            match(Token.TokenType.LeftParen);
            match(Token.TokenType.RightParen);
            match(Token.TokenType.LeftBrace);
            List<Declaration> decls = declarations();
            List<Statement> stmts = statements();
            match(Token.TokenType.RightBrace);

            CProgram p = new CProgram(decls, stmts);
          
            if (error_flag == false)
                Console.WriteLine("No Syntax Error. Comgratulation!");

            return p;
        }

Open in new window

0
Comment
Question by:crazy4s
  • 27
  • 25
  • 2
58 Comments
 
LVL 29

Accepted Solution

by:
Gautham Janardhan earned 416 total points
Comment Utility
if you are trying to get toStringIndented called on to strung it shud be

public override string ToString()
        {
            return return toStringIndented("");
        }

Open in new window

0
 
LVL 29

Expert Comment

by:Gautham Janardhan
Comment Utility
also it wont go to the method unless you call it , and i don't see you calling it in ctor
0
 

Author Comment

by:crazy4s
Comment Utility
do you meant lk this:
but i'm getting the error msg  'AbstractSyntax.CProgram.toString()': no suitable method found to override
public CProgram(List<Declaration> d, List<Statement> b)
        {
            decpart = d;
            body = b;
            toString();
        }

        public override String toString()
        {
            return toStringIndented("");
        }
        public String toStringIndented(String indent)
        {
            string result = indent + "Program(\n";
            foreach(var item in decpart)
                result = result + item.toStringIndented(indent + "  ")  + ",\n";
            foreach(var item in body)
                result = result + item.toStringIndented(indent + "  ")  + ",\n";
            Console.WriteLine(result + indent + ")");
            return result  + indent + ")";
        }

Open in new window

0
 
LVL 25

Expert Comment

by:SStory
Comment Utility
you are missing the override keyword
0
 
LVL 25

Assisted Solution

by:SStory
SStory earned 84 total points
Comment Utility
0
 
LVL 29

Assisted Solution

by:Gautham Janardhan
Gautham Janardhan earned 416 total points
Comment Utility
public override String toString() should be public override String ToString() start with caps t
0
 

Author Comment

by:crazy4s
Comment Utility
hmm what's the difference between toString() and ToString()?
and i got the error msg of:
Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
 At Cprogram.cs line 19, 24, 30
 At Declaration.cs line 27
using System;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AbstractSyntax
{
    public class CProgram
    {
        List<Declaration> decpart = new List<Declaration>();
        List<Statement> body = new List<Statement>();

        public CProgram(List<Declaration> d, List<Statement> b)
        {
            decpart = d;
            body = b;
            ToString();
        }

        public override String ToString()
        {
            return toStringIndented("");
        }
        public String toStringIndented(String indent)
        {
            string result = indent + "Program(\n";
            foreach(var item in decpart)
                result = result + item.toStringIndented(indent + "  ")  + ",\n";
            foreach(var item in body)
                result = result + item.toStringIndented(indent + "  ")  + ",\n";
            Console.WriteLine(result + indent + ")");
            return result  + indent + ")";
        }
    }
}

Open in new window

Declaration.cs
public class Declaration
    {
        public List<Declaration> decl = null;

        public Declaration()
        {

        }

        public Declaration(List<Declaration> Declarations)
        {
            this.decl = Declarations;
            ToString();
        }

        public override String ToString()
        {
            return toStringIndented("");
        }

        public String toStringIndented(String indent)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(indent);
            sb.Append("Declarations(\n");
            int i = 0;
            foreach (Declaration s in decl)
            {
                sb.Append(this.toStringIndented(indent + "  "));
                i++;
                if (i == decl.Count)
                    sb.Append("\n");
                else
                    sb.Append(",\n");
            }
            sb.Append(indent);
            sb.Append(")");
            return sb.ToString();
        }
    }

Open in new window

0
 
LVL 29

Expert Comment

by:Gautham Janardhan
Comment Utility
can u check if "item" is null at line 30.

ToString is declared in object and you are overriding in ur class(using the override key word) while as toString will be a new method in ur class method naes are cases sensitive(no need for override key word).
0
 
LVL 29

Expert Comment

by:Gautham Janardhan
Comment Utility
sorry didnt see the second part, check if decl is null @ line 27 in Declaration.cs
0
 

Author Comment

by:crazy4s
Comment Utility
hmmm i'm having quite alot of classes... and each class i do have a toString() and toStringIndented() method in it? do i need to change all with public override ToString()?
and how do i check if is null?
0
 
LVL 29

Expert Comment

by:Gautham Janardhan
Comment Utility
that wont be needed you can keep it as  toString() , the o/p in the console was not coming because you didn't call it @ ctor.

see code below for null chk , if you have any other classes implemeting toStringIndented you will have to do the same check there as well

 public String toStringIndented(String indent)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(indent);
            sb.Append("Declarations(\n");
            int i = 0;
if(decl != null)
{
            foreach (Declaration s in decl)
            {
                sb.Append(this.toStringIndented(indent + "  "));
                i++;
                if (i == decl.Count)
                    sb.Append("\n");
                else
                    sb.Append(",\n");
            }
}
            sb.Append(indent);
            sb.Append(")");
            return sb.ToString();
        }

Open in new window

0
 

Author Comment

by:crazy4s
Comment Utility
okay looks like the item is null cause i got the below output:
Program (
   Declarations (
      ),
)

and it also go till decpart but not body because statement is not printed out after declarations.
so where is the issue actually?

below is part of my parser.cs
public CProgram program()
        {
            match(Token.TokenType.Int);
            match(Token.TokenType.Main);
            match(Token.TokenType.LeftParen);
            match(Token.TokenType.RightParen);
            match(Token.TokenType.LeftBrace);
            List<Declaration> decls = declarations();
            List<Statement> stmts = statements();
            match(Token.TokenType.RightBrace);

            CProgram p = new CProgram(decls, stmts);
          
            if (error_flag == false)
                Console.WriteLine("No Syntax Error. Comgratulation!");

            return p;
        }

        private List<Declaration> declarations()
        {
            List<Declaration> ds = new List<Declaration>();
            List<Declaration> dsl = new List<Declaration>();
            while (current_token.getType() == Token.TokenType.Int ||
                current_token.getType() == Token.TokenType.Float ||
                current_token.getType() == Token.TokenType.Char ||
                current_token.getType() == Token.TokenType.Bool)
            {
                dsl = declaration();
                ds.AddRange(dsl);
            }
            return ds; 
        }

        private List<Declaration> declaration()
        {
            List<Declaration> result = new List<Declaration>();
            Type t = type();
            Variable v = new Variable(match(Token.TokenType.Identifier));

            if (current_token.getType() == Token.TokenType.LeftBracket)
            {
                match(Token.TokenType.LeftBracket);
                int i = Convert.ToInt32(match(Token.TokenType.IntLiteral));
                match(Token.TokenType.RightBracket);
                ArrayDecl ad = new ArrayDecl(v, t, i);
                result.Add(ad);
            }
            else
            {
                VariableDecl vd = new VariableDecl(v, t);
                result.Add(vd);
            }

            while (current_token.getType() == Token.TokenType.Comma)
            {
                match(Token.TokenType.Comma);
                Variable v1 = new Variable(match(Token.TokenType.Identifier));
                if (current_token.getType() == Token.TokenType.LeftBracket)
                {
                    match(Token.TokenType.LeftBracket);
                    int i = Convert.ToInt32(match(Token.TokenType.IntLiteral));
                    match(Token.TokenType.RightBracket);
                    ArrayDecl ad = new ArrayDecl(v1, t, i);
                    result.Add(ad);
                }
                else
                {
                    VariableDecl vd2 = new VariableDecl(v1, t);
                    result.Add(vd2);
                }
            }

            match(Token.TokenType.Semicolon);

            return result;
        }

        private Type type()
        {
            Type t = null;
            switch (current_token.getType())
            {
                case Token.TokenType.Int:
                case Token.TokenType.Char:
                case Token.TokenType.Float:
                case Token.TokenType.Bool:
                    t = new Type(current_token.toString());
                    current_token = mylexer.next();
                    return t;
                default:
                    Console.WriteLine("Syntax error: line " + mylexer.getCurrentLine() + " expecting: int, char, bool, or float" + "; saw: " + current_token.getType() + "value is " + current_token.toString());
                    current_token = mylexer.next();
                    error_flag = true;
                    break;
            }

            return t;
        }

Open in new window

0
 

Author Comment

by:crazy4s
Comment Utility
it seems like the problem happens here:
it goes to the default constructor but not the constructor with parameter(where i'm passing the declarations into decl), that causes decl to be null?
so how should i deal with this prob?
can anyone help?
public class Declaration
    {
        public List<Declaration> decl = null;

        public Declaration()
        {
            
        }

        public Declaration(List<Declaration> Declarations)
        {
            this.decl = Declarations;
        }

        public String toString()
        {
            return toStringIndented("");
        }

        public String toStringIndented(String indent)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(indent);
            sb.Append("Declarations(\n");
            int i = 0;
            if (decl != null)
            {
                foreach (Declaration s in decl)
                {
                    sb.Append(this.toStringIndented(indent + "  "));
                    i++;
                    if (i == decl.Count)
                        sb.Append("\n");
                    else
                        sb.Append(",\n");
                }
            }
            sb.Append(indent);
            sb.Append(")");
            return sb.ToString();
        }
    }

Open in new window

0
 
LVL 29

Assisted Solution

by:Gautham Janardhan
Gautham Janardhan earned 416 total points
Comment Utility
where are u calling the ctor ? ,  if u want to call the secodn ctor

u shud do soemthign like

Declaration d= new declaratiion(pass arg);

now u shud be doing this

Declaration d = new Decalration();
0
 

Author Comment

by:crazy4s
Comment Utility
in my parser.cs, i'm actually passing a list of declarations:
public CProgram program()
        {
            Console.WriteLine("The program main has the following statements:");
            match(Token.TokenType.Int);
            match(Token.TokenType.Main);
            match(Token.TokenType.LeftParen);
            match(Token.TokenType.RightParen);
            match(Token.TokenType.LeftBrace);
            List<Declaration> decls = declarations();
            List<Statement> stmts = statements();
            match(Token.TokenType.RightBrace);

            CProgram p = new CProgram(decls, stmts);
          
            if (error_flag == false)
                Console.WriteLine("No Syntax Error. Comgratulation!");

            return p;
        }

        private List<Declaration> declarations()
        {
            List<Declaration> ds = new List<Declaration>();
            List<Declaration> dsl = new List<Declaration>();
            while (current_token.getType() == Token.TokenType.Int ||
                current_token.getType() == Token.TokenType.Float ||
                current_token.getType() == Token.TokenType.Char ||
                current_token.getType() == Token.TokenType.Bool)
            {
                dsl = declaration();
                ds.AddRange(dsl);
            }
            return ds; 
        }

        private List<Declaration> declaration()
        {
            List<Declaration> result = new List<Declaration>();
            Type t = type();
            Variable v = new Variable(match(Token.TokenType.Identifier));

            if (current_token.getType() == Token.TokenType.LeftBracket)
            {
                match(Token.TokenType.LeftBracket);
                int i = Convert.ToInt32(match(Token.TokenType.IntLiteral));
                match(Token.TokenType.RightBracket);
                ArrayDecl ad = new ArrayDecl(v, t, i);
                result.Add(ad);
            }
            else
            {
                VariableDecl vd = new VariableDecl(v, t);
                result.Add(vd);
            }

            while (current_token.getType() == Token.TokenType.Comma)
            {
                match(Token.TokenType.Comma);
                Variable v1 = new Variable(match(Token.TokenType.Identifier));
                if (current_token.getType() == Token.TokenType.LeftBracket)
                {
                    match(Token.TokenType.LeftBracket);
                    int i = Convert.ToInt32(match(Token.TokenType.IntLiteral));
                    match(Token.TokenType.RightBracket);
                    ArrayDecl ad = new ArrayDecl(v1, t, i);
                    result.Add(ad);
                }
                else
                {
                    VariableDecl vd2 = new VariableDecl(v1, t);
                    result.Add(vd2);
                }
            }

            match(Token.TokenType.Semicolon);

            return result;
        }

        private Type type()
        {
            Type t = null;
            switch (current_token.getType())
            {
                case Token.TokenType.Int:
                case Token.TokenType.Char:
                case Token.TokenType.Float:
                case Token.TokenType.Bool:
                    t = new Type(current_token.toString());
                    current_token = mylexer.next();
                    return t;
                default:
                    Console.WriteLine("Syntax error: line " + mylexer.getCurrentLine() + " expecting: int, char, bool, or float" + "; saw: " + current_token.getType() + "value is " + current_token.toString());
                    current_token = mylexer.next();
                    error_flag = true;
                    break;
            }

            return t;
        }

Open in new window


in my abstractsyntax.cs (i have CProgram, Declaration, VariableDecl, ArrayDecl... class):
public class CProgram
    {
        List<Declaration> decpart = new List<Declaration>();
        List<Statement> body = new List<Statement>();

        public CProgram(List<Declaration> d, List<Statement> b)
        {
            decpart = d;
            body = b;
            ToString();
        }

        public override String ToString()
        {
            return toStringIndented("");
        }
        public String toStringIndented(String indent)
        {
            string result = indent + "Program(\n";
            foreach (var item in decpart)
                result = result + item.toStringIndented(indent + "  ") + ",\n";
            foreach (var item in body)
                result = result + item.toStringIndented(indent + "  ") + ",\n";
            Console.WriteLine(result + indent + ")");
            return result + indent + ")";
        }
    }

public class Declaration
    {
        public List<Declaration> decl = null;

        public Declaration()
        {

        }

        public Declaration(List<Declaration> Declarations)
        {
            this.decl = Declarations;

        }

        public String toString()
        {
            return toStringIndented("");
        }

        public String toStringIndented(String indent)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(indent);
            sb.Append("Declarations(\n");
            int i = 0;
            if (decl != null)
            {
                foreach (Declaration s in decl)
                {
                    sb.Append(this.toStringIndented(indent + "  "));
                    i++;
                    if (i == decl.Count)
                        sb.Append("\n");
                    else
                        sb.Append(",\n");
                }
            }
            sb.Append(indent);
            sb.Append(")");
            return sb.ToString();
        }
    }
public class VariableDecl : Declaration
    {
        Variable v = null;
        Type t = null;

        public VariableDecl(List<Declaration> Declarations)
            : base(Declarations)
        {

        }

        public VariableDecl(Variable v1, Type t1)
            : base()
        {
            v = v1;
            t = t1;
            toString();
        }

        public new String toString()
        {
            return toStringIndented("");
        }

        public new String toStringIndented(String indent)
        {
            Console.WriteLine("Variable Declaration: " + v.toString() + " " + t.toString());
            return indent + "Variable Declaration: " + v.toString() + " " + t.toString();
        }
    }

public class ArrayDecl : Declaration
    {
        Variable v = null;
        Type t = null;
        int size = 0;

        public ArrayDecl(List<Declaration> Declarations)
            : base(Declarations)
        {

        }

        public ArrayDecl(Variable v1, Type t1, int size1)
            : base()
        {
            v = v1;
            t = t1;
            size = size1;
            toString();
        }

        public new String toString()
        {
            return toStringIndented("");
        }

        public new String toStringIndented(String indent)
        {
            Console.WriteLine("Variable Declaration: " + v.toString() + " " + t.toString() + " size is " + size);
            return indent + "Variable Declaration: " + v.toString() + " " + t.toString() + " size is " + size;
        }
    }

Open in new window

0
 
LVL 29

Expert Comment

by:Gautham Janardhan
Comment Utility
if u see line 30 of parser, u are calling the default ctor... thts y ur decl i null..

if u remove the default ctor it will start start throwing error where ever u have it.
0
 

Author Comment

by:crazy4s
Comment Utility
but dsl = declaration(); is actually calling the below declaration method not the abstractsytanx.Declaration right?
0
 

Author Comment

by:crazy4s
Comment Utility
hmmm i was trying to print out each item in the decpart in CProgram.cs instead of passing to Declaration class(toStringIndented method)...
            foreach (Declaration item in decpart)
                Console.WriteLine(item);

but it prints out AbstractSyntax.VariableDecl instead of the value.
can't really think of any idea to print out list of declarations at a time, any idea?

    public class CProgram
    {
        private List<Declaration> decpart = new List<Declaration>();

        private List<Statement> body = new List<Statement>();

        public CProgram(List<Declaration> d, List<Statement> b)
        {
            decpart = d;
            body = b;
            ToString();
        }

        public override String ToString()
        {
            return toStringIndented("");
        }
        public String toStringIndented(String indent)
        {

            string result = indent + "Program(\n";
            foreach (Declaration item in decpart)
                Console.WriteLine(item);
                //result = result + item.toStringIndented(indent + "  ")  + ",\n";
            foreach(var item in body)
                result = result + item.toStringIndented(indent + "  ")  + ",\n";
            //Console.WriteLine(result + indent + ")");
            return result  + indent + ")";
        }

Open in new window

0
 
LVL 29

Expert Comment

by:Gautham Janardhan
Comment Utility
for this to work "Console.WriteLine(item);" you need to implement ToString method in your classes like i have told you before, note that here method names are CASE SENSITIVE, so toString is not ToString.
0
 

Author Comment

by:crazy4s
Comment Utility
i do have the ToString method in CProgram (see the code that i last posted)
0
 
LVL 29

Expert Comment

by:Gautham Janardhan
Comment Utility
but you are doing Concole.WriteLine on decl and  ToString is not overridden there
0
 

Author Comment

by:crazy4s
Comment Utility
hmm sorry i'm abit confused which one are u referring to: the CProgram or the Declaration?
my Console.WriteLine is supposed to be in decpart (in CProgram)?

CProgram.cs:
public class CProgram
    {
        private List<Declaration> decpart = new List<Declaration>();

        private List<Statement> body = new List<Statement>();

        public CProgram(List<Declaration> d, List<Statement> b)
        {
            decpart = d;
            body = b;
            ToString();
        }

        public override String ToString()
        {
            return toStringIndented("");
        }
        public String toStringIndented(String indent)
        {
            string result = indent + "Program(\n";
            //Console.WriteLine(result);
            foreach (Declaration item in decpart)
            {
                result = result + item.toStringIndented(indent + "  ") + ",\n";
                //Console.WriteLine(item);
            }
            foreach(var item in body)
                result = result + item.toStringIndented(indent + "  ")  + ",\n";
            //Console.WriteLine(result + indent + ")");
            return result  + indent + ")";
        }
    }

Open in new window


Declaration.cs:
public class Declaration
    {
        public List<Declaration> decl = null;

        public Declaration()
        {

        }

        public Declaration(List<Declaration> Declarations)
        {
            this.decl = Declarations;
        }


        public String toString()
        {
            return toStringIndented("");
        }

        public String toStringIndented(String indent)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(indent);
            sb.Append("Declarations(\n");
            int i = 0;
            if (decl != null)
            {
                //Console.WriteLine("decl is not NULL!");
                foreach (Declaration s in decl)
                {
                    sb.Append(s.toStringIndented(indent + "  "));
                    i++;
                    if (i == decl.Count)
                        sb.Append("\n");
                    else
                        sb.Append(",\n");
                }
            }
            sb.Append(indent);
            sb.Append(")");
            return sb.ToString();
        }
    }

Open in new window

0
 
LVL 29

Expert Comment

by:Gautham Janardhan
Comment Utility
in your previous post @ CProgram Line 23, there was a Console.WriteLine on item which was of type declaration, in the latest one this is not there. so this should work
0
 

Author Comment

by:crazy4s
Comment Utility
but when i try to print out from Declaration.cs: it doesn't print out anything?

        public String toString()
        {
            return toStringIndented("");
        }

        public String toStringIndented(String indent)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(indent);
            sb.Append("Declarations(\n");
            int i = 0;
            if (decl != null)
            {
                Console.WriteLine("decl is not NULL!");
                foreach (Declaration s in decl)
                {
                    sb.Append(s.toStringIndented(indent + "  "));
                    i++;
                    if (i == decl.Count)
                        sb.Append("\n");
                    else
                        sb.Append(",\n");
                }
            }
            sb.Append(indent);
            sb.Append(")");
            Console.WriteLine(sb.ToString());
            return sb.ToString();
        }

Open in new window

0
 
LVL 29

Expert Comment

by:Gautham Janardhan
Comment Utility
are you sure

if (decl != null)
            {

Open in new window


is passing ?

what get printed when u run the application
0
 

Author Comment

by:crazy4s
Comment Utility
so trying another method to print out from CProgram but it doesn't prints out the value instead it prints out smt like AbstractSyntax.VariableDecl
        public override String ToString()
        {
            return toStringIndented("");
        }
        public String toStringIndented(String indent)
        {
            string result = indent + "Program(\n";
            foreach (Declaration item in decpart)
                result = result + item.ToString() + ",\n"; <---this line
            foreach(var item in body)
                result = result + item.toStringIndented(indent + "  ")  + ",\n";
            Console.WriteLine(result + indent + ")");
            return result  + indent + ")";

Open in new window

0
 
LVL 29

Expert Comment

by:Gautham Janardhan
Comment Utility
change line 9 to

result = result + item.toString()

remeber method names are case sennsitive
0
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 

Author Comment

by:crazy4s
Comment Utility
this will call the Declaration.toString() and hence nothing is printed out...
because my decl is null, so how can i pass the decpart(list of declarations from CProgram to Declaration), i actually have a constructor in Declaration that takes a parameter:

        public Declaration(List<Declaration> Declarations)
        {
            this.decl = Declarations; <-- this nvr called, that's why my decl is null
        }
0
 
LVL 29

Expert Comment

by:Gautham Janardhan
Comment Utility
i dont see anywhere in ur code where u are using the second ctr u need to call it thus

Declaration temp = new Declaration( this is what u need to pass to decl );

if u call it like this

Declaration temp = new Declaration();

it will always call the default ctr.
0
 

Author Comment

by:crazy4s
Comment Utility
hmm okay so now i have smt like this but it doesn't print out the value too (instead it prints out AbstractSyntax.VariableDecl in Declaration)

public class CProgram
    {
        private List<Declaration> decpart = new List<Declaration>();

        private List<Statement> body = new List<Statement>();

        public CProgram(List<Declaration> d, List<Statement> b)
        {
            decpart = d;
            body = b;
            ToString();
        }

        public override String ToString()
        {
            return toStringIndented("");
        }
        public String toStringIndented(String indent)
        {
            
            string result = indent + "Program(\n";
            Declaration temp = new Declaration(decpart);
            result = result + temp;

            foreach (var item in body)  <--ignore
                result = result + item.toStringIndented(indent + "  ") + ",\n"; <--ignore
            Console.WriteLine(result + indent + ")");
            return result + indent + ")";
        }
    }

Open in new window


Declaration.cs:
public class Declaration
    {
        public List<Declaration> decl = null;

        public Declaration()
        {

        }

        public Declaration(List<Declaration> Declarations)
        {
            this.decl = Declarations;
            toString();
        }


        public String toString()
        {
            return toStringIndented("");
        }

        public String toStringIndented(String indent)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(indent);
            sb.Append("Declarations(\n");
            int i = 0;
            if (decl != null)
            {
                //Console.WriteLine("decl is not NULL!");
                foreach (Declaration s in decl)
                {
                    sb.Append(s.ToString() + "\n");
                    i++;
                    if (i == decl.Count)
                        sb.Append("\n");
                    else
                        sb.Append(",\n");
                }
            }
            sb.Append(indent);
            sb.Append(")");
            Console.WriteLine(sb.ToString());
            return sb.ToString();
        }
    }

Open in new window

0
 
LVL 29

Expert Comment

by:Gautham Janardhan
Comment Utility
change line 23 to

result = result + temp.toString();
0
 

Author Comment

by:crazy4s
Comment Utility
still the same....
0
 
LVL 29

Expert Comment

by:Gautham Janardhan
Comment Utility
try

result = result + temp.toStringIndented("");
0
 

Author Comment

by:crazy4s
Comment Utility
hmmm still the same output:(
0
 
LVL 29

Expert Comment

by:Gautham Janardhan
Comment Utility
thats strange, what is the o/p now ?
0
 

Author Comment

by:crazy4s
Comment Utility
public class Declaration
    {
        public List<Declaration> decl = null;

        public Declaration()
        {

        }

        public Declaration(List<Declaration> Declarations)
        {
            this.decl = Declarations;
            toString();
        }


        public String toString()
        {
            return toStringIndented("");
        }

        public String toStringIndented(String indent)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(indent);
            sb.Append("Declarations(\n");
            int i = 0;
            if (decl != null)
            {
                //Console.WriteLine("decl is not NULL!");
                foreach (Declaration s in decl)
                {
                    sb.Append(s.ToString());
                    i++;
                    if (i == decl.Count)
                        sb.Append("\n");
                    else
                        sb.Append(",\n");
                }
            }
            sb.Append(indent);
            sb.Append(")");
            //Console.WriteLine(sb.ToString());
            return sb.ToString();
        }
    }

public class CProgram
    {
        private List<Declaration> decpart = new List<Declaration>();

        private List<Statement> body = new List<Statement>();

        public CProgram(List<Declaration> d, List<Statement> b)
        {
            decpart = d;
            body = b;
            ToString();
        }

        public override String ToString()
        {
            return toStringIndented("");
        }
        public String toStringIndented(String indent)
        {
            
            string result = indent + "Program(\n";
            Declaration temp = new Declaration(decpart);
            result = result + temp.toStringIndented("");

            foreach (var item in body)
                result = result + item.toStringIndented(indent + "  ") + ",\n";
            Console.WriteLine(result + indent + ")");
            return result + indent + ")";
        }
    }

Open in new window



the output before Program (are those i printed out at each class - which is also the output i want to get at Declaration too)
the output after Program is the list of Declarations that has passed from CProgram
output
0
 
LVL 29

Expert Comment

by:Gautham Janardhan
Comment Utility
line 33
change to                     sb.Append(s.toString());
0
 

Author Comment

by:crazy4s
Comment Utility
no output for the list:
output2
0
 
LVL 29

Expert Comment

by:Gautham Janardhan
Comment Utility
i think ur decl is null or count = 0 @ line 28, when u are passing values from line 69 can u make sure decpart has some value in it
0
 

Author Comment

by:crazy4s
Comment Utility
okay seems like the values are not passed... and i thinks is because at line 55 nothing seems to return (since i call toString() in my VariableDecl.cs)???

in Parser.cs
public CProgram program()
        {
            Console.WriteLine("The program main has the following statements:");
            match(Token.TokenType.Int);
            match(Token.TokenType.Main);
            match(Token.TokenType.LeftParen);
            match(Token.TokenType.RightParen);
            match(Token.TokenType.LeftBrace);
            List<Declaration> decls = declarations();
            List<Statement> stmts = statements();
            match(Token.TokenType.RightBrace);

            foreach (Declaration s in decls)
                Console.WriteLine(s.ToString()); 

            CProgram p = new CProgram(decls, stmts);
          
            if (error_flag == false)
                Console.WriteLine("No Syntax Error. Comgratulation!");

            return p;
        }

        private List<Declaration> declarations()
        {
            List<Declaration> ds = new List<Declaration>();
            List<Declaration> dsl = new List<Declaration>();
            while (current_token.getType() == Token.TokenType.Int ||
                current_token.getType() == Token.TokenType.Float ||
                current_token.getType() == Token.TokenType.Char ||
                current_token.getType() == Token.TokenType.Bool)
            {
                dsl = declaration();
                ds.AddRange(dsl);
            }
            return ds; 
        }

        private List<Declaration> declaration()
        {
            List<Declaration> result = new List<Declaration>();
            Type t = type();
            Variable v = new Variable(match(Token.TokenType.Identifier));

            if (current_token.getType() == Token.TokenType.LeftBracket)
            {
                match(Token.TokenType.LeftBracket);
                int i = Convert.ToInt32(match(Token.TokenType.IntLiteral));
                match(Token.TokenType.RightBracket);
                ArrayDecl ad = new ArrayDecl(v, t, i);
                result.Add(ad);
            }
            else
            {
                VariableDecl vd = new VariableDecl(v, t);
                result.Add(vd);
            }

            while (current_token.getType() == Token.TokenType.Comma)
            {
                match(Token.TokenType.Comma);
                Variable v1 = new Variable(match(Token.TokenType.Identifier));
                if (current_token.getType() == Token.TokenType.LeftBracket)
                {
                    match(Token.TokenType.LeftBracket);
                    int i = Convert.ToInt32(match(Token.TokenType.IntLiteral));
                    match(Token.TokenType.RightBracket);
                    ArrayDecl ad = new ArrayDecl(v1, t, i);
                    result.Add(ad);
                }
                else
                {
                    VariableDecl vd2 = new VariableDecl(v1, t);
                    result.Add(vd2);
                }
            }

            match(Token.TokenType.Semicolon);

            return result;
        }

Open in new window


VariableDecl.cs (one of the derived class of Declaration) - this should return the string
public class VariableDecl : Declaration
    {
        Variable v = null;
        Type t = null;

        public VariableDecl(List<Declaration> Declarations)
            : base(Declarations)
        {

        }

        public VariableDecl(Variable v1, Type t1)
            : base()
        {
            v = v1;
            t = t1;
            toString();
        }

        public new String toString()
        {
            return toStringIndented("");
        }

        public new String toStringIndented(String indent)
        {
            Console.WriteLine("Variable Declaration: " + v.toString() + " " + t.toString());
            return indent + "Variable Declaration: " + v.toString() + " " + t.toString();
        }
    }

Open in new window

0
 
LVL 29

Expert Comment

by:Gautham Janardhan
Comment Utility
@ line 55 i have this VariableDecl vd = new VariableDecl(v, t); is his what u mean?
0
 

Author Comment

by:crazy4s
Comment Utility
yes because i called toString() in VariableDecl.cs and that doesn't seems to keep the return value from toStringIndented() so i'm assuming that's the reason why the value is not passed.
0
 
LVL 29

Expert Comment

by:Gautham Janardhan
Comment Utility
arent u calling the wrong ctr ? you are passing v& t but not declarations that y your declaration is empty.

The basic problem is that your logic is wrong and nothing to do syntax
0
 
LVL 29

Expert Comment

by:Gautham Janardhan
Comment Utility
also note that your call to tostring will only call the tostring of your clss and not the base class.
0
 

Author Comment

by:crazy4s
Comment Utility
but i do have these-->
List<Declaration> result = new List<Declaration>();

VariableDecl vd = new VariableDecl(v, t); <-- these pass v and t to VariableDecl
                result.Add(vd);  <-- these will add into result
0
 
LVL 29

Expert Comment

by:Gautham Janardhan
Comment Utility
what do u expect to get printed thwn this is called ?

since the decl onject inside this is null it wont print it.
0
 

Author Comment

by:crazy4s
Comment Utility
hmm i want to print out the v and t when it gets to VariableDecl
and for the below line i assume there's something to be returned to vd and store it into result.
VariableDecl vd = new VariableDecl(v, t);

i'm a little confuse on how should i pass these so i'm stuck in these part.
or maybe don't look at my code, can you just simply explain a better way to do this?
0
 
LVL 29

Assisted Solution

by:Gautham Janardhan
Gautham Janardhan earned 416 total points
Comment Utility
1) when an object is initialized you don't have to return anything from the ctr,

if you do Person p = new Person();

"p" will always be initialized to a new person object

2) If you want to pass values to a constructor say for instace name of a person to person object , you do it thu the ctr.

public class Person
{
public string PersonName{get;set;}

public Person ()
{
// of this ctr is called person name wont get passed
}

public Person (string personName)
{
PersonName = personName;
}
}

Open in new window



and you use it as

Person p = new Person() ; // this wont pass person name so in this case person name value in person will be null
Person p = new Person("Gautham") ; // passing person name

Open in new window

0
 

Author Comment

by:crazy4s
Comment Utility
okay so let's say if i have a list of persons:
List<Person> persons
if p is added to the above list, can i just do persons.Add(p)?
and "Gautham" is added to the list of persons?
0
 
LVL 29

Expert Comment

by:Gautham Janardhan
Comment Utility
given that u initialise persons first

List<Person> persons = new List<Person>();
Person p = new Person("Gautham")

persons .Add(p);

Console.WriteLine(persons[0].PersonName); // this will print gautham

Open in new window

0
 

Author Comment

by:crazy4s
Comment Utility
but how if i want to print the whole list instead of one, i should use foreach( Person pe in persons) and do the Console.Writeline(pe)?
0
 
LVL 29

Expert Comment

by:Gautham Janardhan
Comment Utility
List<Person> persons = new List<Person>();
Person p = new Person("Gautham")

persons .Add(p);


foreach(Person p in persons )
{
       Console.WriteLine(p.ToString()); // this will print gautham if you override ToString as shown below in class otherwise this will print class name.

Console.WriteLine(p.PersonName); // this will print gautham
}


public class Person
{
public string PersonName{get;set;}

public Person ()
{
// of this ctr is called person name wont get passed
}

public Person (string personName)
{
PersonName = personName;
}

public override ToString() // remeber these are case sensitive toString is not ToString
{
return this.PersonName ;
}
}

Open in new window

0
 

Author Comment

by:crazy4s
Comment Utility
how if my constructor takes more than one parameter, let's say:
Person p = new Person("Gautham", 20) <-- name and age(int).
Does p contains both parameters?
and is that possible to retrieve p (with both parameters) from other methods by returning p?

hmmm not sure whether you understand what i'm trying to ask but maybe an ex lk below:
so when i do print_Statement will the "source" that's being passed will get all 3 parameters (op, exp1, exp2) and prints the value too?
        private IAssignment assignment()
        {
            IVariable target = Factory.create_Variable(match(Token.TokenType.Identifier));
            match(Token.TokenType.Assign);
            IExpression source = expression();
            match(Token.TokenType.Semicolon);
            IAssignment a = Factory.create_Assignment(target, source);
            a.print_Statement();
            return a;
        }

        private IExpression expression()
        {
            IExpression exp1 = conjunction();
            while (current_token.getType() == Token.TokenType.Or)
            {
                Token.TokenType op;
                op = current_token.getType();
                IExpression exp2 = conjunction();
                exp1 = Factory.create_Binary(op, exp1, exp2);
                exp1.print_Expression();
            }
            return exp1;
        }
0
 
LVL 29

Assisted Solution

by:Gautham Janardhan
Gautham Janardhan earned 416 total points
Comment Utility
you will need a new property inside person to hold value for age.. see below

public class Person
{
public string PersonName{get;set;}
public int Age{get;set;}

public Person ()
{
// of this ctr is called person name wont get passed
}

public Person (string personName,int age)
{
PersonName = personName;
Age = age;
}

public override ToString()
{
return string.format("Name - {0} , Age - {1} ",this.PersonName ,this.Age);
}
}

Open in new window

0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Whether you've completed a degree in computer sciences or you're a self-taught programmer, writing your first lines of code in the real world is always a challenge. Here are some of the most common pitfalls for new programmers.
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now