Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an Array for the first time

Tags:

java

My assignment is : Create a Class to store 100 integers in an Array. Call your class “SimpleArray”, and store it in a file called “SimpleArray.java”. All code should go in the main() method. First declare an array of 100 integers. Use a for loop to store the numbers between 500 and 599 in the array. Then build a second loop to print out the data in this array.

This is what I have.

public class SimpleArray {
    public static void main(String[] args) {
        int[] myArray = new int[100];

        for (int i = 0; i < myArray.length; i++) {
            myArray[i] = i + 1;
        }   

        for (int y = 500; y < 599; y++) {
            System.out.println(myArray[y]);
        }
    }
}

Any help would be appreciated I don't quite understand how to do the two different loops. My program works, but it doesn't do what my assignment asks for it to do.

like image 747
Haley Newbold Avatar asked Nov 16 '25 12:11

Haley Newbold


1 Answers

Firstly to store the numbers

for (int i = 0; i < myArray.length; i++) {
    myArray[i] = i + 500;  // store [0] = 0 + 500, [1] = 1 + 500 etc
}   

and then to print

for (int y = 0; y < myArray.length; y++)
        System.out.println(myArray[y]);
}

There is also an easier way to print the entire array

    for (int val : myArray) {
        System.out.println(val);
    }
like image 100
Scary Wombat Avatar answered Nov 19 '25 02:11

Scary Wombat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!