Sunday 21 February 2016

Java Tutorial 3 - More Basics

Last Time
Last time we looked at printing "Hello World" and saw that we could change the text to print different words

This Tutorial
In this tutorial we'll look at doing some more interesting things with the print command

Basic arithmetic
Look at this line
System.out.println("Hello World");
We can see that it will print whatever is between the two brackets. Note that we need speech marks, because we want to literally print what we told it. Let's try telling it to print 3+4

System.out.println("3 + 4");


It should literally print out "3 + 4" because we put it in speech marks. However, if we remove the speech marks:

System.out.println(3 + 4);

It should print 7, as it will actually do the calculation rather than taking it literally. Give it a go and see if it works.

Similarly, you can use minus, multiplication and division. See the table below
Add +
Subtract -
Multiply *
Divide /

Try some of these and see what happens. Note that it will also follow the BIDMAS rules, that is it will not calculate based on the order it was typed but rather it will do brackets, then divisions then multiplications then subtractions and finally additions.
So
3 + 4 * 2 = 11 not 14
Because the 4 * 2 is calculated first to get 8, then the 3 is added. We could of course change this by adding brackets
(3 + 4) * 2 = 14

So now we can do some basic maths with the print command, next time we'll look at saving the results we get and using them later in the program!

If you have any questions feel free to leave a comment and I'll try my best to help

No comments:

Post a Comment