|
Hello all,
I am currently trying to write a loop that fills an array with 12 elements and then compares the length of that array with another array. If both arrays have equal length it prints them. If not an error code comes up. Here is my code
import java.util.*;
class myArrays
{
int allMonths;
String months;
String numbers;
int numberslength;
public void printArray(){
String[] months = new String[13];
months [1] = "January";
months [2] = "Feb";
months [3] = "Mar";
months [4] = "April";
months [5] = "May";
months [6] = "June";
months [7] = "July";
months [8] = "Aug";
months [9] = "Sept";
months [10] = "Oct";
months [11] = "Nov";
months [12] = "Dec";
///allMonths=months.length;
int array[] = new int[14];
int p=0;
//
// Arrays.fill(array, x);
// for (int x=0; x<array.length; x++) {
// Arrays.fill(array, p++);
//
// }
//
// //}
for(int i=0; i<months.length;i++){
Arrays.fill(array, p++);
if (array.length==months.length){
System.out.println("they are same length");
}
System.out.println(array[p]+"."+ months);
}
|
|
|
public class ArrayStart {
public static void main(String[] args) {
int numElements = 12;
String[] months = new String[numElements];
// Reference each element by its index in the array
// starting at index = zero. So the last element of
// an array is index = array.length-1
months[0] = "January";
months[1] = "Feb";
months[2] = "Mar";
months[3] = "April";
months[4] = "May";
months[5] = "June";
months[6] = "July";
months[7] = "Aug";
months[8] = "Sep";
months[9] = "Oct";
months[10] = "Nov";
months[11] = "Dec";
// Check our work.
print(months);
int[] someInts = new int[14];
// Java initializes each element of this array with
// the value of zero.
print(someInts, "someInts before initialization");
// Initialize someInts.
for(int j = 0; j < someInts.length; j++)
someInts[j] = j;
print(someInts, "someInts after initialization ");
int[] moreInts = new int[12];
for(int j = 0, k = 1; j < moreInts.length; j++, k++)
moreInts[j] = k*k;
if(moreInts.length == months.length) {
System.out.println("these two arrays have the same length:");
print(moreInts, "moreInts");
print(months);
}
// If you are using j2se 1.5+ you can skip the two print methods
// and do this for printing arrays:
//System.out.printf("months = %s%n", java.util.Arrays.toString(months));
}
private static void print(String[] array) {
System.out.print("[");
for(int j = 0; j < array.length; j++) {
System.out.print(array[j]);
if(j < array.length-1)
System.out.print(", ");
}
System.out.print("]\n");
}
private static void print(int[] array, String s) {
System.out.print(s + " = [");
for(int j = 0; j < array.length; j++) {
System.out.print(array[j]);
if(j < array.length-1)
System.out.print(", ");
}
System.out.print("]\n");
}
}
|
|
|
|
|
|
|
|
|
|