Click here to Skip to main content
15,885,873 members
Articles / Programming Languages / Java

Java for Beginners - Part 3

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
21 Oct 2012CPOL5 min read 10.2K   105   6  
Java for beginners

Calculator (Functions Or Methods)

Welcome to your third Java for beginners tutorial. In this tutorial, you will learn the simple hello Me program after you've learned Hello World! and Hello Me!..

Things You Will Need

  1. You can download Java if it isn't already installed from the Java official site free Java.
  2. You can download NetBeans for free from the NetBeans official site free NetBeans.
  3. Read Hello Me! if you didn't read it yet from here.
  4. 10 minutes of your time.

NOTE: It's advised to download and install Java before installing NetBeans.

Let's Start

Now that you are ready to make your third program after installing Java and NetBeans, let's open NetBeans, now you will have to create a new project. There are a lot of project types you can choose from but we will start with the simplest and very basic one of them - the Java application.

File>>New Project

You will get a window similar to this (it may look different depending on the version of your NetBeans and other installed programs you have or have not).

New Project

Project Type

Choose Java for the Categories then Java Application for the Projects then Next>.

Project Name

Project Name

For the name, type Calculator or whatever you like your program name to be. But in here, I will be using Calculator as the project name so it's a good practice to do the same so that names won't make you confused.

Now that you created the project, it's time to start writing some codes. This is how your code will look like when you open Calculator.java file.

Java
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package calculator;
/**
 *
 * @author YourName
 */
public class Calculator {
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
    }
}

Our program is very simple. All we want to do is to make our program ask you to insert a number, then second one and then add them and give you the result. To make the program read anything from the Output Window, we create an object from the Scanner Class we will also use variables in this program.

NOTE: Variables are containers that hold our data temporarily. It has many types as we may need to store text or numbers or anything else.

Java
text = String       ex:"This is sentence"
number = int      ex: 1
point number = float       ex: 1.5

NOTE: Scanner Class is a simple text scanner which can parse primitive types and strings using regular expressions.

Now let's make our program ask for the first number. In the Main type System.out.Println("Please enter the first number");. Now we need to create an object of Scanner Class and name it input or whatever you want.

Java
Scanner input= new Scanner(System.in);

Then we need to get the first number from the Output window, so we will declare a variable called num1 of type integer and put your first number there first. Here is how to declare a variable of type int.

Java
int num1;

It's as easy as that but we need to tell our program to put your number in this variable because now we reserved an integer space in our memory and never used it and this is how to tell your program to read your number from the Output window and put it in the variable num1.

Java
int num1 = input.nextInt();

We will do the same with the other number and create another variable called num2. Now all we need to do is to add the two numbers and display the result which is simple as we learned before how to display any text on the Output window but there is a little thing we will add there because we want the program to output num1 + num2 = result so you will notice the difference when we reach this step, but now we will make a function or method which are the same.

NOTE: Function is a block of code to be used in different places in the same code. This is how we declare the function:

Java
private static String add(int x, int y)
{

}

When we declare a function, we first set if it's going to be public or private which simply means if it is private, then we can't use it out of this code file. If it is public, then we can, then we declare that it's static which will be explained in later tutorials, then we set the return type which means that this function will return a text for me in our case, then we set the function name which can be whatever you want here I called it add, then between the brackets we put our arguments which are values we will be using in the function. Here, I put 2 variables of type int because we will send our 2 numbers to our function.

NOTE: If your function won't return any values, you can use void as the return type.

NOTE: Functions must be declared outside the Main function.

Java
private static String add(int x, int y)
{
        int result=x+y;
        return String.format("%d + %d = %d", x,y,result);
}

In our function, we simply declared another variable which is the result and added our 2 numbers and put the sum in the result variable then we returned the string and we used format to make our output in a specific format which is num1 + num2 = result.

Then, all we need to do is to call our function and display its return value and this is how:

C#
System.out.println(add(num1,num2));

Now that is how your final code will look like:

Java
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hellome;
import java.util.Scanner;
/**
 *
 * @author YourName
 */
public class HelloMe {
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        System.out.print("Please enter the first number");
        Scanner name= new Scanner(System.in);
        int num1 = input.nextInt();
        System.out.print("Please enter the second number");
        int num2 = input.nextInt();
        System.out.println(add(num1,num2));
    }

    private static String add(int x, int y)
   {
        int result=x+y;
        return String.format("%d + %d = %d", x,y,result);
   }
}

Now let's run our program and see what we did. Press F6 to run your program.

Output Result

The Result

Congratulations! Now you are done with your third Java program and you are ready to learn more.

Hope you enjoyed and benefited from this tutorial. Please feel free to comment or ask about anything and more tutorials will be added.

Thank you for reading and enjoy your day.

This article was originally posted at http://feeds.feedburner.com/developwareblog

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Egypt Egypt
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --