views:

170

answers:

2

How do I write a constructor to change ints to ints or longs or strings....I am making a Memory system and I have code for Memory and a Memory Element (MemEl) and my test code and I am trying to write these constructors: MemEl(int), MemEl(long), MemEl(String) I already have done it for shorts and bytes but I need some help with these. Thanks.

Here is my Memory code:

class Memory{
    private MemEl[] memArray;
    private int size;
    public Memory(int s)
    {size = s;
        memArray = new MemEl[s];
        for(int i = 0; i < s; i++)
            memArray[i] = new MemEl();
    }
    public void write (int loc, int val)
    {if (loc >=0 && loc < size)
            memArray[loc].write(val);
        else
            System.out.println("Index Not in Domain");
    }
    public MemEl read (int loc)
    {return memArray[loc];
    }
    public void dump()
    {
        for(int i = 0; i < size; i++)
            if(i%1 == 0)
                System.out.println(memArray[i].read());
            else
                System.out.print(memArray[i].read());
    }
}

Here is my Memory Element Code:

class MemEl{

    private int elements;
    public Memory MemEl[];
    {
        elements = 0;
    }
    public void  MemEl(byte b)
    {
        elements = b;
    }
    public void MemEl(short s)
    {
        elements = s;
    }
    public int read()
    {
        return elements;
    }
    public void write(int val)
    {
        elements = val;
    }

}

Here is my Test code

class Test{
    public static void main(String[] args)
    {
        int size = 100;
        Memory mymem;
        mymem = new Memory(size);
        mymem.write(98,4444444);
        mymem.write(96,1111111111);
        MemEl elements;
        elements = mymem.read(98);
        System.out.println(mymem);
        mymem.dump();
        }
}
+1  A: 

elements is an int. byte and short can be cast implicitly (without you knowing) to int. long and String can't, hence you will not be able to add a constructor to the MemEl class

Thirler
+1  A: 

If you can afford to lose precision, then you can cast:

public MemEl(long longValue) {
    elements = (int) longValue;
}

and parse:

public MemEL(String str) {
    elements = Integer.parseInt(str);
}
Bozho