You are on page 1of 2

import java.util.

*;
public class ArrayConcepts
{
public static void main (String [] args)
{
// To create an array, you need to know how big to make it
String [] blah = new String[6]; // holds 6 values
System.out.print("How big should the second array be? ");
Scanner sc = new Scanner(System.in);
int size = sc.nextInt();
sc.nextLine(); // clear input buffer
int [] myArray = new int[size];
// Option 1: user-provided starting values
// Use the 'length' field to determine loop rounds
for (int i = 0; i < blah.length; i = i + 1)
{
System.out.print("Enter a word: ");
blah[i] = sc.nextLine(); // assign input to next slot in
array
}
// Option 2: Use a loop to generate initial values according
// to some pattern
for (int i = 0; i < myArray.length; i = i + 1)
{
// Fill with even #s starting from 0
myArray[i] = 2 * i;
}
// Option 3: Use an initializer list
// This is ONLY possible at time of declaration
int [] foo = {23, 56, -12, 8, 11, 4};
// Cannot print an array directly
System.out.println(myArray);
printArray(myArray);
printArray(foo);
printArray(blah);
printBackwards(myArray);
System.out.println(average(myArray));
}
// Helper methods to print the contents of an array
static void printArray(int [] list)
{
System.out.print("[ ");
for (int x = 0; x < list.length; x = x + 1)
{
System.out.print(list[x] + " ");
}
System.out.println("]");
}

static void printArray(String [] list)


{
System.out.print("[ ");
for (int x = 0; x < list.length; x = x + 1)
{
System.out.print(list[x] + " ");
}
System.out.println("]");
}
static void printBackwards (int [] list)
{
for (int i = list.length - 1; i >= 0; i = i - 1)
{
System.out.print(list[i] + " ");
}
System.out.println(); // go to next line
}
static int sum (int [ ] foo)
{
int total = 0;
for (int i = 0; i < foo.length; i = i + 1)
{
total = total + foo[i];
}
return total;
}
static int average (int [ ] list)
{
return sum(list) / list.length;
}
}

You might also like