Archive | Tutorial RSS for this section

Java Tutorial: Math Class

Every Tuesday I take some time to put together a Java tutorial.  You will notice at the top there is a page indexing them all.  Enjoy!

So turns out, I forgot yesterday was Tuesday so this Java tutorial is a day late!  Since I don’t have to many readers yet, that’s okay I guess.  So today I am going to go over the math class, and also some additional resources.  I wont be touching on all of the methods of the Math class in this tutorial, but some that might be useful, and at the bottom I am going to link off to the documentation of the Math class on Oracles website.

Because Math is in the java.lang package, it does not need to be explicitly imported.  This means there is no need for an import statement, so we will start off our program the same way we have been.  Here is a generic way of showing how to utilize the Math class.

Math.method();

Pretty simple right?  Just make sure that Math has a capital M and there is a . between Math and whichever method of Math you are using.  Since we have not gone over methods in detail I will go over that once I show some of the useful methods of Math, and go from there.

Math.abs(some numeric value);   <----returns the absolute value of a number.

Math.exp(double);               <-----returns the constant e raised to the double.

Math.log(double);               <-----returns the natural log of the double.

Math.max(value, value);         <------returns the max of two numbers (type int, float or double).

Math.min(value, value);         <------returns the min of two numbers (type int, float or double).

Math.pow(double, double);       <-------returns the value of the first argument raised to the second argument.

Now this is just a sample of the different methods the Math class has.  To see the full list go here.  Now onto methods.  What is a method?  I like to describe it as an action a class can perform.  Math being the class, each of these things after the . are the actions that Math can perform.  So you want to find the absolute value of a number?  Pass the number as an  argument to the method.  This is easier to show than tell:

Math.abs(argument);

--or--

Math.abs(-12);

The first example shows that the argument is passed inside the parenthesis to the method, and the second example shows you how that might look.  You can also pass variables, and not just literals.  Just check the documentation to make sure the data type of the variable you are trying to pass matches the data type the method is expecting.  In the case of the Math class, it is usually just a number of some type (float, double, int) and usually not a String.

If you have any questions or need clarification, please leave a comment and I can get that sorted out for you!

Edit: Another way to use the Math class is as follows, to save time!

import static java.lang.Math.*;

public class MathTest
{
    public static void main(String[] args)
    {
        System.out.println(abs(-12));
    }
}

As you can see, there is a different way of importing.  While you don’t need to import the Math class for it to work, this will keep you from having to keep using Math.method() every time.  All you need to put in your file is the following:

import static java.lang.Math.*;

Once you have that, you can call the methods as if they were functions.  In the example above, you see that I am using the abs method of the Math class to find the absolute value of -12.  This works for all of the methods.

Thanks Phoxis for pointing this edit out!

 

Practice Problem

Make a program that asks the user for 5 numbers, and it will determine which is the maximum number, and which is the minimum number.

Also try using all of the different Math methods, and try passing it arguments through literals AND variables.  Have fun!

Advertisements

Java Tutorial: While Loop

Every Tuesday I take some time to put together a java tutorial.  You will notice at the top there is a page indexing them all.  Enjoy!

It has been a couple weeks, but I am back with a new installment of Java Tutorials!

Last time we left off with for loops, and how to use them.  As you noticed, these are very powerful, and they are not even Java specific!  Most programming languages has loops at the core of their abilities.  And usually when you learn the concepts of a loop, the ideas are applied the same (although the syntax might be different.)

But there is more than just the for loop!  There is also the while loop.  It also takes a condition, and repeats the code inside the loop until the condition is met.  Why might we want a different loop?  Can’t we use the for loop for all of our looping needs?  Those are fair questions, and the for loop is quite powerful, but I will give you one reason to want the while loop.

While there are many other reasons, the biggest reason is to keep an entire program running until the user wants to quit.  Sure, you can have a single run through of a program, but most of the time the user might want to go through the process again.  This is especially true about games.  Wouldn’t it be quite annoying to finish a multiplayer match of Call of Duty just to get booted out of the game, and have to restart it?  That would drive most people insane.  So the idea is to keep the program looping back to the multiplayer menu until the user decides to quit.

Lets take a look at a while loop example:

char continue;

boolean quit = false;

while(!quit)

{

    //run the bulk of your program here

    //don't forget to check if the user wants to quit, otherwise there will be an infinite loop!

    System.out.println("Do you want to quit? (y or n);

    continue = scan.nextChar();

    //check to see if the user chose to quit.  If they didn't, keep the loop going.

    if (continue == 'n' || continue =='N')
    {

        quit = true;
    }

}

Practice Problem

Another use is if you want the user to input as many numbers as they want, and then to find the average of those numbers.  Without predetermining the number of inputs, you can use a while loop to keep going until they enter an escape character or number.

So this practice problem is to take numbers as input from the user, and find the average of those numbers.  If you want, you can also do an outer while loop to allow the user to enter a new set of numbers without restarting the program!  Have fun!

Java Tutorial: For Loop

Every Tuesday I take some time to put together a java tutorial.  You will notice at the top there is a page indexing them all.  Enjoy!

Welcome back everyone!  Today is going to be a pretty short tutorial as it is only going over one topic.  Although this topic is pretty important and I consider it part one, as you will see next week.  But enough chit chat, lets get into for loops!

When a programmer want to repeat a piece of code until a certain constraint is met a for loop might be the answer!  What it does is sets up a chunk of code that gets repeated until the for statement is false.  Here is an example of a for loop

int i;

for (i = 0; i < 10; i++)

{

    //Any code you want to repeat goes here

    System.out.println("This is the " + i + " time through the loop");

}

This is this basic structure of the for loop.  There are three arguments that need to be met within the for statement, and they are separated by semicolons.  The first is the variable that will be iterated.  This is the integer variable i in this case and it is set to 0.  The next part is the statement that determines if the loop is done or not.  In this case, as long as the variable i is less than 10 the inner block of code will execute.  The last part is adding 1 to i every time it executes.  You can also do i– for decrement, or any other way to change the variable (might want to multiply it by 2 or something).

This last part of modifying the variable in some way is very important, and it needs to make logical sense.  You want to have some limit, otherwise you will find yourself caught in an infinite loop. Those are bad, so stay away from them!  If you do happen to get stuck in an infinite loop, terminate the program and look at how you defined the for loop to pin point the issue.

While the concept of this may seem silly or a little bit overkill for this far in the tutorial it will become a really amazing asset in the future, so practice your for loops now so they are second nature in the future!

Practice Problem

Okay, so this was a short tutorial but this practice problem should incorporate what you have learned so far!  Ask the user how many times they would like you to repeat a greeting, or any other saying you want.  Then use that to limit your for loop to repeat it that many times!

Java Tutorial: If-else Statements

In the last tutorial we left off with getting user input as well as creating variables.  A common thing to want to do with data, whether it is from user input or stored in another way,  is to have the program make “decisions” with the given information.  The reason I put decisions in quotes is because it is up to the programmer to decide what the program will do based off of given information.  But I think this is best seen through an example.  I am not going to set up an entire program for this tutorial, but just do fragments with all the important information.

int num = 10;

if (num < 5 )

{

    System.out.println("The number is less than 5!");

}

else

{

    System.out.println("The number is greater than 5!");

}

 

There we have it, the most basic if-else statement.  Well I guess that isn’t entirely true, the most basic is just an if statement without an else.  And important thing to remember is that you can have an if without an else, but you can’t have an else without an if.  Say that five times fast!

I initialized the integer variable num to the value 10, and I set up the if-else statement accordingly.  For the first part of the statement the condition is num < 5.  If you have knowledge of math symbols you will know that this is read as num is less than 5.

So in this case if the number stored in num is less than 5, the code that follows in the braces will be executed.  However if this statement is false, it will go to the else, and execute the block of codes immediately after it.  In this case which one executes?  If you said the else block then you are correct!  To write it in a more generic way would be as follows:

if (condition)

{

    Some code you want to execute if the if condition is true;

}

else

{

    Execute this code if the if condition is false;

}

 

Pretty simple right?  Now you might be wondering what kind of statements are legal to use in an if statement, so I am going to put them all in a table right here.

Logical Operators in Java

  • <        less than
  • >        greater than
  • <=     less than or equal
  • >=     greater than or equal
  • ==     equivalent
  • !=      does not equal
This should allow you to do any logical comparison against variables you have.  Of course for boolean variables you would only be checking if they are equivalent or not because there is no way to say true is less than false or the other way around.  Another thing you might want to do is have two statements and only do something if they are both true, or at least on is true.  This is referred to as logical and (&&) and logical or (||).  If you put one of these between the two statements in the if declaration it will make the statement true if both sides are true (using and) or if at least one side is true (using or).  Here is an example:
int age = 20;
String name = "Brett";
//using logical and
if (age <= 18 && name == "Brett")
{
    System.out.println("Hello Brett!");
}
else
{ System.out.println("You are not Brett!");
}
//using logical or
if (age <= 18 || name = "Brett")
{
    System.out.println("You are either at least 18 years old or Brett, not sure which though!");
}
else
{
    System.out.println("You are not Brett and you are not at least 18.");
}
 

You can play around with these different logical operators, but if you really thing about it you don’t need to guess in check if you use the proper planning.  There is one more thing that I want to add to this tutorial before ending it and that is that you can do more than just if-else.  You can do if-else if-else.  There can be multiple else if in this statement and I will show you an example that we are all too familiar with.
if (grade <= 90)
{
    System.out.println("You got an A");
}
else if (grade <= 80)
{
    System.out.println("You got a B");
}
else if (grade <= 70)
{
    System.out.println("You got a C");
}
else if (grade <= 60)
{
    System.out.println("You got a D");
}
else
{ System.out.println("You got an F");
}

As you can see there were multiple else if statements, and if one is false, it goes and checks the next statement until it finds the correct block to execute.  That concludes this java tutorial, again if you have any questions feel free to leave a comment and I will get back to you as soon as possible.

Practice Problem
Make an interactive story where the user chooses which path to take, and depending on their choice have different blocks of code execute.  Have fun!

Java Tutorial: User Interaction

In the first tutorial I discussed how to set up a very simple java program, if you have not checked it out or forgot how you can find it here.  If you do remember how to set it up then lets get started!

Last program wasn’t to interesting I will admit but it was a start.  In this tutorial we will discuss how to set up your program to get user input!  Say we want to ask a user for their age, instead of statically typing in our age using the print statement.  We need to ask the user for their age, and then store that name into a variable and use the information stored in that variable within our print statement!  Here is an example of the code to do this.

import java.util.Scanner;

class UserAge

{

    public static void main(String[] args)

    {

         Scanner scan = new Scanner(System.in);

         int userAge;

         System.out.print("Please enter your age: ");

         userAge = scan.nextInt();

         System.out.println("Your age is " + userAge);

    }

}

Okay now it might look a little intimidating at this point, but have no fear all will be revealed!  Lets look at the first line in the source code a little bit.

import java.util.Scanner;

This is an import statement and will be used whenever you want to bring in a class from an outside source.  In this case the scanner is in the util package of java.  Because it is a class you will need to make sure you make Scanner uppercase otherwise you will encounter an error.  This class is what you will use any time you want to get input from a user.  The next couple lines should look familiar from the previous tutorial as the class name and the main function definition.  Something I forgot to mention is that I will go over the importance of String[] args at a future date, but for now just put it there just because.  The next couple of lines are new though.

Scanner scan = new Scanner(System.in);

int userAge;

The first is the creation of a new object and the second is the creation of a new variable.  As you can see they are a little different but don’t worry to much about the details of an object.  That is a more advanced topic that will be covered later.  You will notice some similarities in the declarations though.  Both start with the type followed by the name.  In the case of creating the scanner the type is Scanner and the name is scan.  The other side of the equals sign is the creation of the new Scanner object and passing it the nessesary parameter that will be needed to read the user input.  Like I said don’t worry to much about the details just yet, and just type it in the way you see it here.

The way the variable is created is very similar except with the int data type we don’t need to create an object.  In this case the variable has the name userAge.  There are many primitive data types for storing information but I will list some of the ones that will be used the most within this series of tutorials.

Data Types:

  • int – stores integers (ex:1, 33, -322)
  • float – stores floating point numbers (ex: 1.3, 22.3455)
  • String – stores a string of letters
  • boolean – stores true or false

While this list does not hold all of the data types, the ones I left out are very similar to ones I listed that can be found using Google if you find these data types to be too small.  Now that we have covered the different data types and how to declare variables we can go to the next section of code.

System.out.print("Please enter your age: ");

userAge = scan.nextInt();

System.out.println("Your age is  " + userAge);

The first part of this block of code should be familiar from before.  The only thing I want to point out is that I used print here because I wanted the user to enter their age right after the colon so it looked a little cleaner.  The next line is new though, and it is assigning the next integer entered by the user to the variable userAge that we created earlier.  nextInt() is a method scan that gets the next integer, and the equals sign assigns userAge that variable.  The of course we have another print statement, but this time there is a new element. The + userAge after the string is called string concatenation.  Essentially we are tacking on whatever is in the variable userAge to the end of our string literal.  If you forget to close the quotes before adding the variable it will literally print the variable userAge rather than the integer stored in it.  This is just a nice way to show the user that you got their input!

Next Time

That is the end of this java tutorial! Next time we will discuss a very simple yet powerful tool.  The if-else statement.  If you haven’t already and you are interested in learning out to program, please like and follow so you can get my new tutorials as they come out.  But don’t quit reading yet there is still a practice problem for this tutorial.

Practice Problem

I think a good way to get this idea down pat is to make your own version of Mad Libs.  This will allow you to use string concatenation as well as use the scanner class.  Try to use as many data types as you can, and don’t forget that when you are getting a name or any string of text use the String data type.  Do note that it is a capital S in this case, while the other primitives are lowercase.  Good luck and have fun!