Join Peggy Fisher for an in-depth discussion in this video Understanding arrays, part of Learning Java.
- If you wanted to write an application that is used to keep track of all items on a grocery list, this is easy when there's only a few items. But what if you need to buy 100 items or even more than 100. Then you would need at least 100 string variables just for the name of the items and another 100 double variables for the price of each item because it would include both the dollars and cents. So it includes the fractional portion. As you can see, this is getting pretty complicated fast. As you guessed it, there is a better way.
We can use a special type of data structure called an array. This is a tool used in most programming languages that allows us to store and work with multiple values of the same data type using a single variable name. The values in the array are stored in consecutive memory locations. The syntax for creating an array is data type, such as int, or double, character, string. Then you use a open square bracket and a close square bracket. The square brackets are what indicate to the computer that it's an array.
Then you give it a name. A variable name. And you set it equal to New which is a keyword, data type, again, you have to repeat the data type, that was on the left-hand side, brackets, size, bracket and a semicolon. Arrays must be declared with the size or a list of values which is called an initializer list. Each element in the array is accessed using an index value, which indicates it's position in memory. Note, the index values always start with zero.
This is going to be very important, as we start to use arrays. There is one more item of caution. Beware of the out-of-bounds error. Since arrays are a fixed size, if you try to access data at an index value greater than the size of the array, your program will end abruptly during execution, because this is not checked ahead of time by the compiler. Okay, let's write a program, that allows the user to enter the price of five items. We will save the prices in an array, and then add them together and print the total.
I've already created a project called Grocery List. I'm gonna start by adding the array! So, I'm going to remove the comment, To Do Code Application Here, and I'm going to type in the data type. We said prices, need to include decimal, so I want to use double, square bracket, square bracket, space, and then an array name. Let's call it Prices, and we set that equal to a new array, a new double array. Again, make sure that the data type on the right, matches the data type on the left, and we have to give it a size.
Let's go ahead and keep track of five prices. Okay, now I want to ask the user to enter in the price of each item, but in order to do that, I need to use the Scanner Class. So let's go up here to Line five, and let's import the Scanner Class. So, Import, Java.Util.Scanner. Now, I can go back down to Line 17, and create an instance of the Scanner Class. So, Scanner, space. I'm going to name my variable, In, equals a new instance, so New Scanner, and I need to tell it that it's supposed to read from the System, from the Console, so System.In.
If you're follow along, make sure you note the capitalization. Remember, Java is case sensitive. Okay. Now I can ask the user to enter in the five prices. So, in order to prompt the user, I have to write a message out to the Console. So, I'm going to do System.Out.PrintLn, which will print a message and then go to the next line, and I'm going to say, Enter Five Prices. Now I can read the prices into my array. Remember, I have to specify the index value of each item.
So, I'm going to do Prices, bracket. Where do I start? At zero. Good. This again is really important, equals In.nextDouble. We need to repeat this for the next four prices. Okay. Notice that my index values started at zero, and since there's five items, the last index value is a four. If I tried to access the fifth element, remember, it would cause an error in my program, and my program would end abruptly.
Okay. Now, I can calculate the total by adding up each element in the array. I need to create a variable to hold the total, so I'm going to do Double Total is equal to Prices at index value zero, and I need to continue with each of the elements in the array. Okay, don't forget your semicolon at the end of the line. It's kind of like a period at the end of a sentence. Syntax for a programming language is a lot like grammar is to English. You have to have something at the end of each statement.
Now, that I calculated the total, let's print it back out again. System.Out.PrintLn to print line, and I'm going to print out the total. The total for all five items is, and I need to include the total. So remember, earlier we talked about strings, we talked about concatenating. I'm going to add, using a plus sign, and I'm going to add the variable Total. So when it prints to the screen, it will print out the literal that's in double quotes, plus the value that's in the variable called Total.
Okay, let's run our program. It says enter five prices. I'm going to enter five prices. $10.00, $5.50, $4.75, $3.90, and one more, $11.75. The total for all five items, is 35.9. One note here is it's nice to format the output, to include a dollar sign and make sure that both of the decimal points show up.
Let's go back to our program, and instead of doing a PrintLn, I'm going to change this to a PrintF to talk about formatting. So PrintF, and now I need to add the format code. I want to do a dollar sign and then I'm going to put five positions to the left of the decimal, point two, to get two positions to the right, and I specify that it's a floating point number, because it includes a decimal, with the letter F. The tricky part here, is instead of doing plus Total, I want to do comma, cause it's going to take the Total variable and it's going to put it wherever the symbol is, percent sign five point two F, it's going to replace that with the value Total.
Okay, let's try it again. I'm just going to enter random prices and one more. A pack of gum. You can see that looks much better. The total for all five items is $25.40. There is a much more detailed section on arrays later in the course.
- Downloading and exploring NetBeans
- Understanding Java basics: data types, strings, arrays, and more
- Controlling flow with functions and loops
- Creating classes
- Sorting and searching arrays
- Manipulating files
- Handling errors
- Building GUIs