Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Well done!
You have completed Practice Java Arrays!
You have completed Practice Java Arrays!
Preview
See how I solve the problem in this video!
This video doesn't have any notes.
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
All right, did you figure it out?
0:00
Here's my solution.
0:02
First, we need to create an array of good
cow names.
0:04
So I'll start by creating a new string
array called names
0:07
and setting it equal to a few names
that I like.
0:12
Remember, to create an array literal,
0:15
we can use the brackets
and add the names in the middle.
0:17
I'll go with maple, moana,
0:22
and milkshake.
0:26
Awesome.
0:29
Next, we need to create an array of cows
that's the same length as our names array.
0:30
So create an array of cows called cows
0:36
and set it equal to new cow.
0:39
Then we need to pass in an argument
for how long the array is.
0:43
We could just type 3,
but we can also type in names.length.
0:48
Next, we need to use a for loop
to populate our new cows array
0:54
with new cows
using the names from the names array.
1:00
Let's start by just creating a for loop.
1:04
For int i equals zero, and we'll loop
1:07
while i is less than names.link.
1:11
We could also use
three or cows if we wanted to
1:15
Then we need to increment i
1:20
by one and add the body of our
for loop with brackets
1:22
Inside the for loop
1:28
we need to set cows at position
i equal to a new cow
1:29
with the name from the names array at the
i position
1:35
Perfect.
1:40
Finally,
we want to use an enhance for loop
1:42
or for each loop
to print the name of each cow.
1:46
For cow, and we'll name it cow,
1:51
so a cow in the cows array,
1:54
and for each cow in the cows array,
1:57
let's print out the name of the cow.
2:00
So we'll do system.out.printf,
then we'll use percent s
2:03
for our placeholder,
and %n to add a new line.
2:09
Then we need to fill in our placeholder
with cow.getName
2:13
to retrieve the name
and a semicolon to finish it off.
2:19
And last
but not least, we just need to run it.
2:24
Write a command to clear the workspace,
2:27
compile our arrays.java file,
2:31
and run it using the Java command.
2:34
And there you go.
2:41
We got cows
named Maple, Moana, and Milkshake.
2:42
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up