-
Array Constructor
I am trying to write code for a class that has a 40element array in it and i want to use the 2nd set of code to just input the numbers and print it out for now. I have to do a bunch with the ints later but i cannot figure out how to write the constructor.
I am not sure if I have given enough information for someone to help, but I do not know what else to do. I have spents hours looking at this. Thanks for your help.
public class HugeInteger
{
//Instance Variables
int[] hugeArray=new int [41];
//constructor
HugeInteger(
{
}//End Constructor
}//End Class
*************************
{
public static void main(String args[])
{
// smaller numbers
HugeInteger i = new HugeInteger(9999);
HugeInteger j = new HugeInteger(1);
HugeInteger k = new HugeInteger(-9999);
HugeInteger l = new HugeInteger(-1);
System.out.println(i);
}
}
-
Code:
public class HugeIntegerTest
{
public static void main(String[] args)
{
// smaller numbers
HugeInteger hugeInt = new HugeInteger();
hugeInt.addElement(9999);
hugeInt.addElement(1);
hugeInt.addElement(-9999);
hugeInt.addElement(-1);
System.out.println(hugeInt);
}
}
class HugeInteger
{
//Instance Variables
int numberOfElements = 40;
// The jvm initializes all elemnts to zero by default.
int[] hugeArray=new int [numberOfElements];
int index = 0;
//constructor
HugeInteger()
{
// Check assertion above:
for(int i = 0; i < hugeArray.length; i++) {
System.out.print(hugeArray[i]);
if(i < hugeArray.length-1)
System.out.print(", ");
else
System.out.println();
}
}//End Constructor
public void addElement(int n)
{
// Assign element at index to the local variable/
// arguemnt value "n".
hugeArray[index] = n;
// Increment index.
index++;
// If the array is full, ie, index > 39
// do something...
if(index > numberOfElements-1) {
System.out.println("array is full!");
// Next call to this method will cause an
// ArrayIndexoutOfBoundsException.
// Start over:
index = 0;
}
}
public String toString()
{
return java.util.Arrays.toString(hugeArray);
}
}//End Class