Java Tutorial #6 Fun with vectors!
Previous tutorial https://steemit.com/java/@nicetea/java-tutorial-5-serializable-writing-objects-to-a-file-and-accessing-them
In this tutorial, we will be using vectors to store daily temperature data and printing this data out to the console.
So let's get directly started with the code:
import java.util.Vector;
public static void main(String args[]) {
final int DAYS = 31;
String result;
Vector<Double> temperature = new Vector<Double>(DAYS);
Double temp = new Double(5.3);
for (int i = 0; i < temperature.capacity(); i++)
temperature.add(temp);
result = "Day\tTemperature\n";
for (int i = 0; i < temperature.size(); i++)
result += i + 1 + "\t" + temperature.get(i).doubleValue() + "\n";
System.out.println(result);
}
So firstly, we will set a final variable DAYS, to set the count of days we want to get the data stored to. In our case it's 31(1 month).
Next, we are declaring a result variable and the actual temperature vector, as well as the temp, which will store the current's temperature on the day.
So in the first for loop, we are going to iterate until we reached the maximum capacity(maximum possible size) of the vector by using temperature.capacity(). Inside the first for loop, the temp will be added to the temperature vector.
Now, the head of our output is printed, for a better overview as you can see in the screenshot below.
The second for loop iterates until the maximum size(actual, filled size) is reached. The number of the day i and the temperature value temperature.get(i).doubleValue() will be added to the string result.
Lastly, the result is printed out and you will see an output like this:
Stay tuned!
Maaaan, why does Java have to be so strict and verbose about things, why can't it just have fun like python xD
But seriously, nice tut!
Haha, yeah Python is awesome too!
Thanks for the knowledge share. The community needs as much of it as it can :D