Quick Java Help

Joined
Dec 14, 2009
Messages
1
Reaction score
0
I'm making a small program for my class to set up a variable-length array that the user inputs values to. The problem is that I don't know how to set up an empty constructor to work with the user input, I only know how to make one that the programmer inputs values into. (using jgrasp)

Class:
//***********************************
//
// Array.java Patrick Sweeney
//
//***********************************

public class Array
{

private int[] list;



public Array (int ... nums)
{
list = nums;

}


public String toString()
{
String result = "";

int[] temp = new int[list.length];
for (int num = 0; num < list.length; num++)
{
temp[num] = list[num];
}
for (int nums : temp)
{
result += nums + " ";
}
return result;
}


public String Power()
{
String result = "";
double[] temp = new double[list.length];
for (int num = 0; num < list.length; num++)
{
temp[num] = list[num];
temp[num] = Math.pow(num, 3);
}
for (double nums : temp)
{
result += nums + " ";
}
return result;
}

public int Sum()
{
int result = 0;

for (int nums : list)
{
result += nums;
}
return result;
}

public double Average()
{
int sum = 0, length;
double avg;

for (int nums : list)
{
sum += nums;
}


length = list.length;
avg = sum / length;

return avg;
}

}


Driver:

//***********************************
//
// ArrayTester.java Patrick Sweeney
//
//***********************************
import java.util.Scanner;

public class ArrayTester
{
public static void main (String[] args)
{
int length;

Scanner scan = new Scanner(System.in);

System.out.println ("Enter the size of the array: ");

length = scan.nextInt();

Array numarray = new Array(); //this is where the problem is

for (int index = 0; index < length; index++)
{
System.out.println ("Enter a number: ");

numarray[index] = scan.nextInt();
}

System.out.println ("The array: " + numarray);
System.out.println ("The array raised to power 3: " + numarray.Power());
System.out.println ("The sum of the array: " + numarray.Sum());
System.out.println ("The average of the numbers: " + numarray.Average());
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,982
Messages
2,570,186
Members
46,742
Latest member
AshliMayer

Latest Threads

Top