Java constructor question - java

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

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

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

Related

Generic Linear List based on Arrays

I'm trying to write a Linear List based on arrays, but make the list be able to store any value by using Java Generics. This way I can create other programs that utilize it, but pass in different data types. I'm not entirely sure how to do this, any help would be appreciated.
I guess Im struggling trying to set it up and create the functions. The generic type really messes me up.
For example, trying to add a removeFirst() function, I cant use a loop like this:
for (int i = 0; i < n - 1; i++)
newList[i] = newList[i + 1];
— as it says The type of the expression must be an array type but it resolved to ArrayList.
Fair warning, I'm still learning data structures. This is what I have so far:
import java.util.ArrayList;
public class LinearList<T> {
private static int SIZE = 10;
private int n = 0;
private final ArrayList<T> newList = new ArrayList<T>(SIZE);
private T t;
public void set(T t) {
this.t = t;
}
public T get() {
return t;
}
public void add(T value, int position) {
newList.add(position, value);
n++;
}
public void addFirst(T value) {
newList.add(0, value);
n++;
}
public void removeLast() {
T value = null;
for (int i = 0; i < newList.size(); i++)
value = newList.get(i);
newList.remove(value);
n--;
}
public void removeFirst() {
newList.remove(0);
n--;
}
public T first() {
return newList.get(0);
}
public T last() {
int value = 0;
for (int i = 0; i < newList.size() - 1; i++)
value++;
return newList.get(value);
}
public int count() {
return n;
}
public boolean isFull() {
return (n >= SIZE);
}
public boolean isEmpty() {
return (n <= 0);
}
//part 4
public void Grow() {
int grow = SIZE / 2;
SIZE = SIZE + grow;
}
public void Shrink() {
int grow = SIZE / 2;
SIZE = SIZE - grow;
}
public String toString() {
String outStr = "" + newList;
return outStr;
}
}
A good start would be to make it non-generic with a class you are comfortable with, such as an Integer.
Once you have it set up, you can then make it generic by adding <T> to the class name, then replacing all references of Integer with T.
public class MyArray{ becomes public class MyArray<T>{
public Integer add(Integer value){ becomes public T add(T value){
See What are Generics in Java? for more help

After creating a bigger array, how do I use the new array in other functions of the same class?

It was asked of us to implement this class without built-in functions or Arraylist.
When needing to make the data array bigger, I created a new array and gave it a new size (which is the capacity+10). As the data array is a data member, I can access it from the other functions of the array. However, I can't access the newArray. Can I create a bigger array using the data array? If not,how can I access the new Array from the other functions of the class?
package ADTDynamicArrays;
import java.util.*;
public class DynamicIntgerArray {
public int data[];
int size;
int capacity;
public DynamicIntgerArray(){
data = new int[5];
size = 0;
capacity = 5;
}
public DynamicIntgerArray(int ca){
size=0;
if(ca<5)
capacity=5;
else
capacity=ca;
data=new int[capacity];
}
public boolean checkIndex(int index){
if(index < 0 || index >=data.length)
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
else
return true; }
public void copyOldtoNew(int [] arry1, int arry2[]){
arry2=arry1;
}
public void checkCapacity(int s){
if(capacity<= s){
capacity +=10 ;
int newArray[]=new int[capacity];
copyOldtoNew(data,newArray);
}
}
public void getElement (int index){
}
public int getlength(){
return capacity;
}
public void insertElement(int element){
}
public void replaceElement(int index, int element){
}
public void print(){
}
public void addShiftElements(int index, int element){
}
}
This is the code that was given to us that we have to work with that we cannot modify:
package ADTDynamicArrays;
import java.util.*;
public class DynamicIntgerArray {
public int [] data;
public DynamicIntgerArray(){
data = new int[5];
size = 0;
capacity = 5;}
public DynamicIntgerArray(int ca){
}
public boolean checkIndex(int index){
if(index < 0 || index >=data.length)
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
else
return true; }
public void copyOldtoNew(int [] arry1, int arry2[]){
}
public void checkCapacity(int s){
if(capacity<= s){
capacity +=10 ;
}
}
public void getElement (int index){
}
public int getlength(){
}
public void insetElement(int element){
checkCapacity(size+1);
}
public void replaceElement(int index, int element){
}
public void print(){
}
public void addShiftElements(int index, int element){
if(checkIndex(index)){
checkCapacity(size + 1);
}
}
}
After this code:
int newArray[]=new int[capacity];
copyOldtoNew(data,newArray);
you need this little piece of magic:
data = newArray;
well, I hope you understand it is not magic at all.
You should have to create a new array and then reference data array to it like this way
int oldItems[] = new int[10];// this is your data array
int newItems[] = new int[20];// this is new array created
System.arraycopy(oldItems, 0, newItems, 0, 10);// copy new array to data array
oldItems = newItems;// your data saved and size increased of data array

How to split a string sequence and convert each element to a double

I am stuck on a problem for my programming class. We need to separate the argument String at the commas to produce an array of Strings, then it needs to parse each individual String to get a double, storing these doubles in sequence. We are also given some test code, with input arguments like ("1,5").
Here is my current code
public class Sequence
{
private double[] sequence;
public Sequence(String s)
{
String[] res = s.split(",");
int length = res.length;
double[] result = new double[length];
for ( int i =0; i<length; i++) {
result[i] = Double.parseDouble(res[i])
}
}
Im not sure where to go from here because when i test my code, it dosent give the expected result. What does it mean by store in sequence ?
I have updated my answer, this might be what you are looking for:
import java.util.Arrays;
public class Four {
public static void main(String[] args) {
String string = "1,2,10,4,9";
System.out.println(string);
double[] ds = getDouble(string);
for (int i = 0; i < ds.length; i++) {
System.out.println(ds[i]);
}
}
private static double[] getDouble(String string) {
double[] _double;
String[] _Strings = string.split(",");
_double = new double[_Strings.length];
for (int i = 0; i < _Strings.length; i++) {
_double[i] = Double.parseDouble(_Strings[i]);
}
Arrays.sort(_double);
return _double;
}
}
out put
I would do it this way:
public class Sequence {
private double[] sequence;
public void createSequence(int sequenceLength) {
sequence = new double[sequenceLength];
}
public void addToSequence(int index, double value) {
sequence[index] = value;
}
public double parseDouble(String s) {
return Double.parseDouble(s);
}
public String[] splitString(String s) {
return s.split(",");
}
#Override
public String toString() {
return Arrays.toString(sequence);
}
public static void main(String[] args) {
String str = "10.10,20.20,30.30";
Sequence sequence = new Sequence();
String[] splitted = sequence.splitString(str);
sequence.createSequence(splitted.length);
for (int i = 0; i < splitted.length; i++) {
double doubleValue = sequence.parseDouble(splitted[i]);
sequence.addToSequence(i, doubleValue);
}
System.out.println(sequence);
}
}
change private double[] sequence; to private Double[] sequence;
and use below code
public class Sequence {
private Double[] sequence;
public Sequence(String s) {
String separated[] = s.replace(" ", "").split(",");
ArrayList<Double> list = new ArrayList<>();
for (String num : separated) {
list.add(Double.parseDouble(num));
}
this.sequence = list.toArray(new Double[separated.length]);
}
}

implementing a loop using final variables

Is there a way to implement a loop using final variables?
I mean a loop that would run for a specified number of iterations when you are not allowed to change anything after initialization!
Is recursion allowed, or do you literally need a loop construct like for or while? If you can use recursion, then:
void loop(final int n) {
if (n == 0) {
return;
} else {
System.out.println("Count: " + n);
loop(n-1);
}
}
One way is to create an Iterable<Integer> class representing an arbitrary range (without actually having to store all of the values in a list):
public static class FixedIntRange implements Iterable<Integer> {
private final int min;
private final int max;
public FixedIntRange(final int min, final int max) {
this.min = min;
this.max = max;
}
#Override
public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
private Integer next = FixedIntRange.this.min;
#Override
public boolean hasNext() {
return next != null;
}
#Override
public Integer next() {
final Integer ret = next;
next = ret == max ? null : next + 1;
return ret;
}
#Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
}
and then iterate over it normally:
for (final int i : new FixedIntRange(-10, 20)) {
// this will be run for each i in the range [-10, 20]
}
Create an array whose size is the required number of iterations, then use it in a for-each loop:
public class Test {
public static void main(String[] args) {
final int N = 20;
final int[] control = new int[N];
for(final int i : control){
System.out.println(i);
}
}
}
The trick here is that the iteration indexing is generated by the compiler as part of the enhanced for statement, and does not use any user-declared variable.
Something like this -
final int max = 5;
for(int i=0; i<max; i++) {}
Or another interesting one-
final boolean flag = true;
while(flag) {
// keep doing your stuff and break after certain point
}
One more-
List<String> list = ......
for(final Iterator iterator = list.iterator(); iterator.hasNext(); ) {
}

Java - Error Message Help

In the Code, mem is a of Class Memory and getMDR and getMAR ruturn ints. When I try to compile the code I get the following errors.....how can I fix this?
Computer.java:25: write(int,int) in Memory cannot be applied to (int)
Input.getInt(mem.write(cpu.getMDR()));
^
Computer.java:28: write(int,int) in Memory cannot be applied to (int)
mem.write(cpu.getMAR());
Here is the code for Computer:
class Computer{
private Cpu cpu;
private Input in;
private OutPut out;
private Memory mem;
public Computer()
{
Memory mem = new Memory(100);
Input in = new Input();
OutPut out = new OutPut();
Cpu cpu = new Cpu();
System.out.println(in.getInt());
}
public void run()
{
cpu.reset();
cpu.setMDR(mem.read(cpu.getMAR()));
cpu.fetch2();
while (!cpu.stop())
{
cpu.decode();
if (cpu.OutFlag())
OutPut.display(mem.read(cpu.getMAR()));
if (cpu.InFlag())
Input.getInt(mem.write(cpu.getMDR()));
if (cpu.StoreFlag())
{
mem.write(cpu.getMAR());
cpu.getMDR();
}
else
{
cpu.setMDR(mem.read(cpu.getMAR()));
cpu.execute();
cpu.fetch();
cpu.setMDR(mem.read(cpu.getMAR()));
cpu.fetch2();
}
}
}
Here is the code for Memory:
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 int read (int loc)
{return memArray[loc].read();
}
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 the code for getMAR and getMDR:
public int getMAR()
{
return ir.getOpcode();
}
public int getMDR()
{
return mdr.read();
}
Your Memory class has a method write(int, int).
You call it with a single int. As if it was write(int).
Java complains about that: "Computer.java:28: write(int,int) in Memory cannot be applied to (int)". So either you are missing your location (loc) parameter or your value (val) parameter; depending on what code is supposed to be actually doing.

Categories