1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

[Tutorial] Learn Java Programming

Discussion in 'Other Languages' started by buckyaustin, Oct 6, 2013.

  1. buckyaustin

    buckyaustin Newbie

    Joined:
    Aug 27, 2013
    Messages:
    32
    Likes Received:
    24
    Occupation:
    Web Developer
    Location:
    Ireland
    Welcome to buckyaustin's java tutorial. From the creators of Learn xHTML/HTML and CSS.


    One of the most complicated things to start learning is programming. So in this tutorial I hope to open a world of possibilities to you all. At the end of this tutorial you will be well versed in programming jargon. Cause that is all it really is jargon, nothing more nothing less. It isn't even that hard to do. You will notice that as you follow along.


    If you think this is difficult, think again, it is like learning to speak a foreign language. It takes time and practice. I only hope to provide you with the building blocks for this time and practice.


    In this first post I just want to get you set up and to learn the basics. I mean the very basics.
    Ok download eclipse IDE and the Java Development Kit (JDK). Install the JDK, restart your computer then install Eclipse. There is an additional step in Windows where you have to open Eclipse and point eclipse to the JDK. But I won't be explaining that because it is on the eclipse website.


    On Linux open up the command line and type dependent on distro;
    [Debian (.deb)]
    Code:
       
    
    sudo apt-get install openjdk-7-jre eclipse
    [password]
    
    

    [Red Hat (.rpm)]

    Code:
    su
     [password]
     yum install openjdk-7-jre eclipse
    
    

    Restart your computer. Open up eclipse, it will ask you for a workspace, Type in the location where you want to store your programs. I use ?\home\unknown\workspace\?. Eclipse will even create the folder if it doesn't exist.


    Now this is where I have to explain naming conventions. Projects start with an upper case. Packages come after this and start with a lower-case. Classes come after packages and start with upper case. Then after Classes there is variables which start with a lower-case. Any way notice that it is in the order upper, lower, upper, lower. This is called camel cassing and all programming languages use it. The reason for this is to allow the programmer to know what they are using, a package or a variable. Even thou you should know what you are using this does help.


    OK go to file, click new, click project. Name it anything you want. Right click on your project, new, package. Name the package conversion. Right click conversion. Click new and Class. Name the class CurrencyConverter.


    The reason you named the package conversion was because the package can hold many different converter programs, and you will want to make the name meaningful but at the same time abstract.
    The left side of eclipse is called the package explorer. The middle is the text editor. And the bottom is the console. The top is the toolbar.


    Ok go to the text editor and make sure you have this in your CurrencyConverter


    Code:
    [FONT=Times New Roman][SIZE=3]/* 
    Author:  buckyaustin
    Date:      06/10/2013[/SIZE][/FONT]
    [FONT=Times New Roman][SIZE=3]Purpose: To present user with a menu. And display them output[/SIZE][/FONT]
    [FONT=Times New Roman][SIZE=3]Version:  Version 1[/SIZE][/FONT]
    [FONT=Times New Roman][SIZE=3]*/[/SIZE][/FONT]
     
    [FONT=Times New Roman][SIZE=3]public class CurrencyConverter[/SIZE][/FONT]
    [FONT=Times New Roman][SIZE=3]{//start of class[/SIZE][/FONT][INDENT] [FONT=Times New Roman][SIZE=3]public static void main(String [] args) [/SIZE][/FONT] 
    [/INDENT]
    [INDENT][FONT=Times New Roman][SIZE=3]{//start of main method
    [/SIZE][/FONT]
    [/INDENT]
    [INDENT=2] [FONT=Times New Roman][SIZE=3]//lets display an attractive title to our program[/SIZE][/FONT][/INDENT]
    [INDENT]  [FONT=Times New Roman][SIZE=3]        System.[I]out[/I].println("\t\t Currency Converter!");
    
    [/SIZE][/FONT][/INDENT]
    [INDENT=2] [FONT=Times New Roman][SIZE=3]//Display the menu for the user to choose from.[/SIZE][/FONT]
    [/INDENT]
    [INDENT]  [FONT=Times New Roman][SIZE=3]        System.[I]out[/I].print("1: \t Convert to US Dollar." +[/SIZE][/FONT][/INDENT]
    [INDENT=3]             [FONT=Times New Roman][SIZE=3]"2: \t Convert to AUS Dollar." +[/SIZE][/FONT]
    [/INDENT]
    [INDENT=4]     [FONT=Times New Roman][SIZE=3]"3: \t Convert to STG. \n");
    
    [/SIZE][/FONT]
    [/INDENT]
    [INDENT][FONT=Times New Roman][SIZE=3]}//end of main method[/SIZE][/FONT]
    [/INDENT]
    [FONT=Times New Roman][SIZE=3]}//end of class[/SIZE][/FONT]
    [COLOR=#000000]
    [/COLOR]


    Breakdown;



    1. The '/*' and '*/' are the start and end of a block comment. In this block comment you give information about the program. Which version it is, what has been changed, creators name etc.
    2. The '//' is a single line comment anything that comes after this is just ignored, you add them there just for you or anyone else who is going to be working on the program. Make sure you add enough of these for future reference.
    3. '{' are the start of methods. After these I have added comments, that is because you can easily get confused about which curly bracket belongs where and how many are needed in your program. Each curly bracket gets a line to itself. Opening curly brackets mean on the next line you insert an extra tab, closing brackets mean on the next line you insert one less tab/indent.
    4. 'System.out.print' in any of it's forms is just a way to display on the console. '\t' is called an escape character, it escapes from 'Sytem.out.prints' normal rules and inserts a tab. '\n' is another but this time it means new line.
    5. 'System.out.print' displays anything within it's brackets, but just like math anything in the brackts has to be completed before the rest of the math can be done. So the '+' symbol adds/joins the Strings of output together so it displays the way we want.


    What's next?:


    Well in the next post we will be going onto variables, conditional statements and your first introduction into Object Orientated Programming (OO).​
     
    • Thanks Thanks x 6
    Last edited: Oct 6, 2013
  2. Junkfood00

    Junkfood00 Elite Member

    Joined:
    Sep 13, 2011
    Messages:
    1,949
    Likes Received:
    1,336
    Your post has color issues, rectify them to make the tutorial readable.
     
  3. buckyaustin

    buckyaustin Newbie

    Joined:
    Aug 27, 2013
    Messages:
    32
    Likes Received:
    24
    Occupation:
    Web Developer
    Location:
    Ireland
    Could you pm me the colours of the parts that are not readable to you?That would be much appreciated.
     
  4. Junkfood00

    Junkfood00 Elite Member

    Joined:
    Sep 13, 2011
    Messages:
    1,949
    Likes Received:
    1,336
    Ehh?? Just look yourself, it's the second half of your post.
     
  5. bartosimpsonio

    bartosimpsonio Jr. VIP Jr. VIP Premium Member

    Joined:
    Mar 21, 2013
    Messages:
    8,903
    Likes Received:
    7,492
    Occupation:
    ZLinky2Buy SEO Services
    Location:
    ⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩⇩
    Home Page:
    The text on the textarea here is black, but once published it becomes white. If you invert it here, it becomes black on the main message. I hope this helps you correct that.
     
    • Thanks Thanks x 1
  6. TheeAriGrande

    TheeAriGrande Regular Member

    Joined:
    Jul 14, 2013
    Messages:
    270
    Likes Received:
    151
    Location:
    Candlestick Park
    Fix the "Breakdown", the text color is black. Change it to something other than black please.
     
    • Thanks Thanks x 1
  7. buckyaustin

    buckyaustin Newbie

    Joined:
    Aug 27, 2013
    Messages:
    32
    Likes Received:
    24
    Occupation:
    Web Developer
    Location:
    Ireland
    Thank you so much. I'll try to correct it now.
     
  8. buckyaustin

    buckyaustin Newbie

    Joined:
    Aug 27, 2013
    Messages:
    32
    Likes Received:
    24
    Occupation:
    Web Developer
    Location:
    Ireland
    Thank you, actually it's brown lol same thing thou, not readable
     
  9. buckyaustin

    buckyaustin Newbie

    Joined:
    Aug 27, 2013
    Messages:
    32
    Likes Received:
    24
    Occupation:
    Web Developer
    Location:
    Ireland
    I use the white theme of BHW it makes all posts have a higher contrast, meaning I can read the posts, all posts more rapidly. But yeah I'll check the original post in various themes to see the problems, that seems to be the best solution so far thank you.
     
  10. buckyaustin

    buckyaustin Newbie

    Joined:
    Aug 27, 2013
    Messages:
    32
    Likes Received:
    24
    Occupation:
    Web Developer
    Location:
    Ireland
    Variables and Conditional Statments

    I know I promised an introduction to OO programming in the last post, but that seems to be too much too fast, I believe that the fundamentals would be more important in this stage.


    Welcome to my second post about learning java. So what is a variable? Well a variable is just an allocation in RAM that stores information. There are different types of variables, 'int', 'double', 'char', 'string' and 'Boolean'. I will be going into each of these at some point and time.


    Conditional statements, now what the hell are they. Actually they are quite simple, for instance is it sunny outside is a conditional question, it has two answers yes or no, these are conditional statements. So using these two conditions we can for instance decide to cut the grass or decide to leave it for a sunny day.


    Open up eclipse again, this time go to package explorer and copy CurrencyConverter and paste it into the same package. Name it CurrencyConverterV2 for version two.


    Code:
    /* Author:   buckyaustin
        Date:      07/10/2013
        Purpose:    To present user with a menu. Respond to their choice accordingly
        Version:  Version 2
        Update Log: Added two variables, if else and switch statements.
    */
    
    
    //importing the Scanner class from java/util folder.
    import java.util.Scanner;
    
    
    public classCurrencyConverterV2 
    {//start of class
        public static void main(String[] args) 
        {//start of main method
            
            //creating a variable to store the users choice
            int choice = 0;
    
    
            //creating a variable of the amount the users wants converted
            double euroAmount = 0.0;
    
    
            //an instantiation of the Scanner class
            Scanner keyboardIn = newScanner(System.in);
    
    
            //lets display an attractive title to our program
            System.out.println("\t\tCurrency Converter!");
    
    
            
            //asking the user for the amount to convert
            System.out.print("How much do you want convert? ");
    
    
            //Storing this in euroamount using our new scanner class
            euroAmount =keyboardIn.nextDouble();
    
    
            
            //Display the menu for the user to choose from.
            System.out.print("1:\t Convert to US Dollar." +
                             "2: \tConvert to AUS Dollar." +
                             "3: \t Convertto STG. \n");
    
    
            //an if statement that looks at the users choice and acts dependent on that.
            if (choice == 1) 
            {//start of if
                System.out.println("USDollar conversion chosen");
            }//end of if
     
    
            else if(choice == 2) 
            {//start of else
                System.out.println("AUSDollar conversion chosen");
            }//end of else
    
    
            else if(choice == 3) 
            {//start of else
                System.out.println("STGconversion chosen");
            }//end of else
    
    
            else
            {//start of else
                System.out.println("Invalid Choice made");
            }//end of else
    
    
    
            
            //a switch statement that looks at the users choice and acts dependent on that
            switch (choice) 
            {//start of switch
    
    
            case1:    System.out.println("US Dollar conversion chosen");
                break;
            case 2:   System.out.println("AUS Dollar conversion chosen");
                break;
            case 3:   System.out.println("STG conversion chosen");
                break;
    
            default:  System.out.println("Invalid Choice made");
                break;
            }//end of switch
    
    
            
            /*notice how switches are smaller?
             * The switch and if else do the same thing.
             * They are called conditional statements.
             */
    
    
        }//end of main method
    }//end of class
    

    Breakdown:

    1. We update the block comment to include the new additions to the code.
    2. 'import java.util.Scanner' means use Scanner which is located in java/util/ in this class.
    3. 'int choice', means store a whole number in a box called choice.
    4. 'double euroAmount', means store a decimal number in a box called euroAmount.
    5. 'Scanner keyboardIn = new Scanner(System.in)' means create a new version of Scanner called keyboardIn. This is instantiation. Simple isn't it?
    6. The if, else if, and else statements are dependent on what the user enters as their choice. If they enter one go to if, if they enter 2 go else if. And if they enter something outside the range go to the only thing left else.
    7. The switch statement, does the exact same thing as if, just in my opinion is a lot easier to read and learn about. But instead of else we have default.


    Tip:Type "switch" and press [ctrl] + [space], this is called inteli-sense, eclipse is smart enough to give you the basic layout of a switch statement. This can save you a lot of heart ache, it works with everything, from variables the whole way up to packages.


    In the next post you will be learning about loops in all it's variations. This is where we start to see a more useful program,because this version still has a lot of problems. The main one right now is that it doesn't allow the user to choose when the program should end, it just ends. We will be fixing that.
     
    • Thanks Thanks x 2
    Last edited: Oct 7, 2013
  11. buckybrendan

    buckybrendan Registered Member

    Joined:
    Aug 6, 2013
    Messages:
    64
    Likes Received:
    72
    Occupation:
    Web Developer
    Location:
    Ireland
    Nice post austin. You fixed the color scheme, its readable now.

    I hope ppl read this tutorial and follow it, as java is a great language to learn first. It will help you begin with whatever language you wish to learn, or if you want to learn java this will be a good tutorial to start with.
     
  12. rob1977

    rob1977 Power Member

    Joined:
    Mar 25, 2013
    Messages:
    773
    Likes Received:
    666
    Cheers for this (I've just spotted it)

    I've been following Brendan html css tut's and thought they were great learned loads.

    Looking forward to having a bash at this to thanks very much
     
  13. buckyaustin

    buckyaustin Newbie

    Joined:
    Aug 27, 2013
    Messages:
    32
    Likes Received:
    24
    Occupation:
    Web Developer
    Location:
    Ireland
    Thanks for your kind words man, yeah were bro's me and Brendan. He was told to join BHW, and he informed me of how good BHW was.

    I hope people are noticing that this is process of creating a fully working program from the beginning to the finish. All explained. I am also trying to push it in a way to be more useful and relievant to the readers, in the exact same way a business want you to code.
     
  14. buckyaustin

    buckyaustin Newbie

    Joined:
    Aug 27, 2013
    Messages:
    32
    Likes Received:
    24
    Occupation:
    Web Developer
    Location:
    Ireland
    Iteration[HR][/HR]


    Welcome to buckyaustin's Java tutorial, I promised to teach you all about loops, well iteration is repeating math over and over, which is just a loop. I did say that programming was just jargon and not complicated. Also we will be moving onto OO programming and user input.

    There are three types of loops in Java. The do while loop, while loop and the for loop.

    The while loop;

    The while loop is a loop that checks the boolean statement first. If the boolean is false the loop does not continue and if true the loop continues. This type of loop can repeat forever, this is called an infinite loop.

    The do while loop;

    The do while loop is a loop that checks the boolean at the end, this means that do while loop will run at least once. This type of loop can repeat forever. Again causing an infinite loop.

    The for loop;

    The for loop is a predefined loop, this means that the loop will end after the amount of repeats required. For example add 1 to x until 10, x = 1. This would create 1,2,3,4,5,6,7,8,9,10. We knew that it would end at 10, that is predefined.

    To show you the syntax of each of these I will present three different versions of the same program. OK go to project explorer in eclipse and copy and paste Currencyconverterv2 it three times. Call these new classes Currencyconverterv3DO, Currencyconverterv3While and Currencyconverterv3For. Remove the if else statements from each. Update the block comment at the top.

    The while loop;
    Code:
    /* Author:      buckyaustin
        Date:         08/10/2013
        Purpose:    To present user with a menu. Respond to their choice accordingly and to calculate the conversion
        Version:     Version 3
        Update Log: Added while loop, and calculated the conversions, delete if else statement.
    */
    
    //importing the Scanner class from java/util folder.
    import java.util.Scanner;
    
    public class CurrencyConverterV3While[INDENT]{//start of class
        public static void main(String[] args) 
        {//start of main method[/INDENT]
    [INDENT=2]  
      //creating a variable to store the users choice which has to be outside the loop, otherwise
      //it can't use it.
      int choice = 0;
      
      while (choice != 4) [/INDENT]
    [INDENT=2]  {//start of while loop, while loop checks choice here
    [/INDENT]
    [INDENT=3]   
       //creating a variable of the amount the users wants converted
       double euroAmount = 0.0;
       //an instantiation of the Scanner class
       Scanner keyboardIn = new Scanner(System.in);
        
       //lets display an attractive title to our program
       System.out.println("\t\t Currency Converter!");
      
       //asking the user for the amount to convert
       System.out.print("How much do you want convert? ");
       //Storing this in euroAmount using our new scanner class
       euroAmount = keyboardIn.nextDouble();
      
       //Display the menu for the user to choose from.
       System.out.print("1: \t Convert to US Dollar." +[/INDENT]
    [INDENT=5]               "2: \t Convert to AUS Dollar." +
    [/INDENT]
    [INDENT=6]       "3: \t Convert to STG. \n");
    [/INDENT]
    [INDENT=3]   choice = keyboardIn.nextInt();
      
       //a switch statement that looks at the users choice and acts dependent on that
       switch (choice) 
       {//start of switch
    [/INDENT]
    [INDENT=4]   //the case statements calculate the conversion, then displays $Conversion is the US Dollar conversion
       case 1:    System.out.println("$" + euroAmount * 1.35 + " is the US Dollar conversion.");
        break;
       case 2: System.out.println("$" + euroAmount * 1.44 + " is the Aus Dollar conversion.");
        break;
       case 3: System.out.println("£" + euroAmount * 0.84 + " is the Sterling conversion.");
        break;
       case 4: System.out.println("Exiting program.");[/INDENT]
    [INDENT=6]System.exit(0);
    [/INDENT]
    [INDENT=4]     break;
       default:System.out.println("Invalid Choice made");
        break;
    [/INDENT]
    [INDENT=3]   }//end of switch
    [/INDENT]
    [INDENT=2]}//end of while loop
    [/INDENT]
    [INDENT=3]  
    [/INDENT]
    [INDENT]    }//end of main method
    [/INDENT]
    }//end of class
    
    
    The do while loop;
    Code:
    /* Author:      buckyaustin
        Date:         08/10/2013
        Purpose:    To present user with a menu. Respond to their choice accordingly and to calculate the conversion
        Version:     Version 3
        Update Log: Added do loop, and calculated the conversions, delete if else statement.
    */
    
    //importing the Scanner class from java/util folder.
    import java.util.Scanner;
    
    public class CurrencyConverterV3DO[INDENT]{//start of class
        public static void main(String[] args) 
        {//start of main method[/INDENT]
    [INDENT=2]  
      //creating a variable to store the users choice which has to be outside the do loop, otherwise
      //it can't use it.
      int choice = 0;
      
      do 
      {//start of do which means everything gets done over and over till the user exits[/INDENT]
    [INDENT=3]   
       //creating a variable of the amount the users wants converted
       double euroAmount = 0.0;
       //an instantiation of the Scanner class
       Scanner keyboardIn = new Scanner(System.in);
        
       //lets display an attractive title to our program
       System.out.println("\t\t Currency Converter!");
      
       //asking the user for the amount to convert
       System.out.print("How much do you want convert? ");
       //Storing this in euroAmount using our new scanner class
       euroAmount = keyboardIn.nextDouble();
      
       //Display the menu for the user to choose from.
       System.out.print("1: \t Convert to US Dollar." +
                  "2: \t Convert to AUS Dollar." +
           "3: \t Convert to STG. \n");
       choice = keyboardIn.nextInt();
      
       //a switch statement that looks at the users choice and acts dependent on that
       switch (choice) 
       {//start of switch[/INDENT]
    [INDENT=4]   //the case statements calculate the conversion, then displays $Conversion is the US Dollar conversion
       case 1:    System.out.println("$" + euroAmount * 1.35 + " is the US Dollar conversion.");
        break;
       case 2: System.out.println("$" + euroAmount * 1.44 + " is the Aus Dollar conversion.");
        break;
       case 3: System.out.println("£" + euroAmount * 0.84 + " is the Sterling conversion.");
        break;
       case 4: System.out.println("Exiting program.");[/INDENT]
    [INDENT=6]System.exit(0);
    [/INDENT]
    [INDENT=4]     break;
       default:System.out.println("Invalid Choice made");
        break;
    [/INDENT]
    [INDENT=3]   }//end of switch
    [/INDENT]
    [INDENT=2]  }while(choice != 4); //end of do while loop. Do while checks choice here.
      
    [/INDENT]
    [INDENT]    }//end of main method
    [/INDENT]
    }//end of class
    
    
    The for loop;
    Code:
    /* Author:      buckyaustin
        Date:         08/10/2013
        Purpose:    To present user with a menu. Respond to their choice accordingly and to calculate the conversion
        Version:     Version 3
       Update Log: Added for loop, and calculated the conversions, delete if else statement.
    */
    
    //importing the Scanner class from java/util folder.
    import java.util.Scanner;
    
    public class CurrencyConverterV3For[INDENT]{//start of class
        public static void main(String[] args) 
        {//start of main method[/INDENT]
    [INDENT=2]  
      //creating a variable to store the users choice which has to be outside the loop, otherwise
      //it can't use it.
      int choice = 0;
      
      for (int i = 0; i <= 10; i++) 
      {//start of for. i=0, i + 1 until i = 10, once that happens exit.
       [/INDENT]
    [INDENT=3]   //creating a variable of the amount the users wants converted
       double euroAmount = 0.0;
       //an instantiation of the Scanner class
       Scanner keyboardIn = new Scanner(System.in);
        
       //lets display an attractive title to our program
       System.out.println("\t\t Currency Converter!");
      
       //asking the user for the amount to convert
       System.out.print("How much do you want convert? ");
       //Storing this in euroAmount using our new scanner class
       euroAmount = keyboardIn.nextDouble();
      
       //Display the menu for the user to choose from.
       System.out.print("1: \t Convert to US Dollar." +[/INDENT]
    [INDENT=5]              "2: \t Convert to AUS Dollar." +
    [/INDENT]
    [INDENT=6]       "3: \t Convert to STG. \n");
    [/INDENT]
    [INDENT=3]   choice = keyboardIn.nextInt();
      
       //a switch statement that looks at the users choice and acts dependent on that
       switch (choice) 
       {//start of switch
    [/INDENT]
    [INDENT=4]   //the case statements calculate the conversion, then displays $Conversion is the US Dollar conversion
       case 1:    System.out.println("$" + euroAmount * 1.35 + " is the US Dollar conversion.");
        break;
       case 2: System.out.println("$" + euroAmount * 1.44 + " is the Aus Dollar conversion.");
        break;
       case 3: System.out.println("£" + euroAmount * 0.84 + " is the Sterling conversion.");
        break;
       case 4: System.out.println("Exiting program.");
         System.exit(0); //this tells the program to exit with no errors. Even breaks the for
         break;
       default:System.out.println("Invalid Choice made");
        break;
    [/INDENT]
    [INDENT=3]   }//end of switch
    [/INDENT]
    [INDENT=2]  }//end of for loop, which can only repeat until i = 10 or the user's choice = 4
      
    [/INDENT]
    [INDENT]    }//end of main method
    [/INDENT]
    }//end of class
    
    
    breakdown;

    For all three, well there similarities.

    1. Each requires user input, there are two ways of doing this, code it yourself or use a piece of code already written. I think I would use a piece of code already written. The piece of code I am referring to is the Scanner class, that we want to use. We don't care how it works, we know it does work. “import java.util.Scanner;”. Import means use, java.util means the location of this class, in java/util on your computer.

    2. That's all well and good, but how can we use it, well to use this Class we have to instantiate it. That means we have to create a new object of that class. When that object is created that is the instant you can use it. The new object is called keyboardIn. “Scanner keyboardIn = new Scanner(System.in);”

    3. “"$" + euroAmount * 1.35 + " is the US Dollar conversion."” This litrealy means, $[amount of US dollars] is the US Dollar conversion. For example 1 * 1.35 = 1.35. So therefore $1.35 is the US Dollar conversion. “*” is called an operation character, in this case the operation is multiply.

    4. choice = keyboardIn.nextInt();, this is where we use the new Scanner class to capture the next integer, whole number, that the user enters and stores the input as choice in RAM.


    For the while and do while loops. Since their only difference is where the check is done.

    1. “while (choice != 4) ” This means if choice is equal to 4, that is true but to exit we need a false. The “!” is means not which makes the true a false. So this means do the code while choice does not equal four. If choice equals three the check returns false, but the not makes it true, so the code is run.

    For the for loop;

    1. “for (int i = 0; i <= 10; i++)”, this means repeat the code for the length required for “i” to be = to 10. The less than means while “i” is less that 10. So therefore this will loop 11 times, 0,1,2,3,4,5,6,7,8,9,10. we create the integer “i” in the for loop, check if it is under 10 or equal, run the code and increase “i” by one and repeat until “i” equals 10. “i++” means increment by 1.
     
    • Thanks Thanks x 1
  15. buckyaustin

    buckyaustin Newbie

    Joined:
    Aug 27, 2013
    Messages:
    32
    Likes Received:
    24
    Occupation:
    Web Developer
    Location:
    Ireland
    Hey guys haven't been on in a couple of days, as you all know sometimes life can get in the way. Well that's enough for excusses, lets get on with more Java. Also if you believe I'm going to fast/slow or should have explained this, that and another thing. Please feel free to tell me.

    Methods[HR][/HR]


    Welcome to buckyaustin's Java tutorial, in this post I will be teaching you about methods and how useful they can be. I will be also discussing global scope variables.

    So what is a method?

    Well a method is a set of steps that can be described in a more abstract way. That being said what does that mean, well a person doesn't need to know how to fix a car to make it work the way they want. Same goes for code, if the method is created, you don't need to know how it works as long as the name somewhat describes what the method does.

    How are they useful?

    Well methods can be used over and over again, but only need to be written out once. You call them when you need to use them, if they need to be updated there is only one place to look for them to make the update. This creates efficiency, also by creating less code it makes debugging much easier. The less code makes your program much smaller and much easier to read, which once again is a good thing.

    What is a global scope variable?


    This is a variable that can be used anywhere within the class. The variables we have seen up until now have only had main method scope because they were declared in the main method, no other piece of the class could use these variables. Any variable created in a loop,switch etc. only has scope to work within the loop,switch etc.

    So lets get on moving. To breakdown what we want this version to do, all we want is to check if the user selects an option on the menu.

    Copy and paste Currencyconverterv3Do, because that's the one we will be using from here on out. Call the new class Currencyconverterv4. Update the block comment at the top. Make sure your version 4 looks like mine.

    Code:
    /* Author:      buckyaustin
        Date:         9/10/2013
        Purpose:    To present user with a menu. Respond to their choice accordingly and to calculate the conversion
        Version:     Version 4
        Update Log: adding a check range method that only allows the user to enter between 1-4
    */
    
    //importing the Scanner class from java/util folder.
    import java.util.Scanner;
    
    public class CurrencyConverterV4 
    {//start of class[INDENT]
        //notice how choice is now outside the main too? But still within the class, this is called
        //a global variable and can be used by anything within the class, but we have to say that  it
        //belongs to the class by stating that it is static to this class.
        static int choice = 0;
        //an instantiation of the Scanner class
        static Scanner keyboardIn = new Scanner(System.in);
        
        public static void main(String[] args) [/INDENT]
    [INDENT=2]{//start of main method
      
      do 
      {//start of do which means everything gets done over and over till the user exits[/INDENT]
    [INDENT=3]   
       //creating a variable of the amount the users wants converted
       double euroAmount = 0.0;
        
       //lets display an attractive title to our program
       System.out.println("\t\t Currency Converter!");
      
       //asking the user for the amount to convert
       System.out.print("How much do you want convert? ");
       //Storing this in euroAmount using our new scanner class
       euroAmount = keyboardIn.nextDouble();
      
       //Display the menu for the user to choose from.
       System.out.print("1: \t Convert to US Dollar." +
                  "2: \t Convert to AUS Dollar." +
           "3: \t Convert to STG. \n");
       
       //taking in the users choice
       choice = keyboardIn.nextInt();
       
       //we need to call the the check range otherwise it's just a pretty piece of code that
       //never gets used. Giving the min to be 1 and the max to be 4
       CheckRange(1, 4);
       
       //a switch statement that looks at the users choice and acts dependent on that
       switch (choice) 
       {//start of switch[/INDENT]
    [INDENT=4]   //the case statements calculate the conversion, then displays $Conversion is the US Dollar conversion
       case 1:    System.out.println("$" + euroAmount * 1.35 + " is the US Dollar conversion.");
        break;
       case 2: System.out.println("$" + euroAmount * 1.44 + " is the Aus Dollar conversion.");
        break;
       case 3: System.out.println("£" + euroAmount * 0.84 + " is the Sterling conversion.");
        break;
       case 4: System.out.println("Exiting program.");
         break;
       default: System.out.println("Invalid Choice made");
        break;
    [/INDENT]
    [INDENT=3]   }//end of switch
    [/INDENT]
    [INDENT=2]  }while(choice != 4); //end of do while loop. Do while checks choice here.
    [/INDENT]
    [INDENT]  
        }//end of main method
        
        /*notice how were outside the main, welcome to OO programming, this is called a method
       We are still within the class so this program now has two methods, the main and the check range.
      */
        
        //this method is just checking if the users choice is outside the min and max,
        //if it is outside the range, asks the user to re-enter the value.
    
        public static void CheckRange(int min, int max)
        {//start of checkrange
    [/INDENT]
    [INDENT=2]  if(choice < min || choice > max)
      {//start of if[/INDENT]
    [INDENT=3]   System.out.println("Please enter a valid choice.");
       choice = keyboardIn.nextInt();
    [/INDENT]
    [INDENT=2]  }//end of if
    [/INDENT]
    [INDENT]    }//end of checkrange
    
    [/INDENT]
    }//end of class
    
    Breakdown;

    • “static Scanner keyboardIn = new Scanner(System.in);” means that the new Scanner object is static to Currencyconverterv4. No other class has access to it. But because of it being outside the main, this new Scanner has global scope.
    • “CheckRange(1, 4);”, this is where we use the CheckRange method, with 1 being the min and 4 being the max. That's all you need to know about it. The menu's options are 1,2,3,4.


    • “public static void CheckRange(int min, int max)”. This is a static method to this class, no other class has access. Void means that it doesn't return anything. We do not need this method to return anything do we? Return means give a value back to where the method is being used. The two integers are called arguments. Meaning when this method gets used it requires two integers to work with.


    • “if(choice < min || choice > max)”. If choice is less than min or choice greater than max run the code within the if, if the user's choice is between the range then don't execute the code. When the user enters above the max or below the min, they are asked to enter a valid option.

    I hope you are starting to get a good grasp of Java, and the theory behind it, this theory is nearly universal to all languages. Even PHP. I also hope your all noticing the problems with this program, and are already trying to solve the problems. If not don't worry I will be going through everything as we progress.

    In the next post, I will being going into how your main method should look in every program you create from now on by taking methods to the extreme for this program. After that we will be taking a break from coding and I will try to explain everything again, and tell you all the secret of how I made these programs by explaining standards.
     
    • Thanks Thanks x 1
  16. Gophering

    Gophering Junior Member Premium Member

    Joined:
    Mar 21, 2013
    Messages:
    115
    Likes Received:
    279
    Occupation:
    Unemployed
    Location:
    EU
    Can't wait till we get to the factory factory factories!

    Just kidding. Good job OP.
     
  17. Chris22

    Chris22 Regular Member

    Joined:
    Sep 29, 2010
    Messages:
    400
    Likes Received:
    1,059
    I'm stoked for the IOC container for the factory factory factories, that's when it gets intense
     
  18. buckyaustin

    buckyaustin Newbie

    Joined:
    Aug 27, 2013
    Messages:
    32
    Likes Received:
    24
    Occupation:
    Web Developer
    Location:
    Ireland
    Thanks guys, I do actually get the jokes, but I really don't want anyone here to try and use what I am teaching to get jobs, I want the readers to make there own ways, I just hope to help them through that path.
     
  19. buckyaustin

    buckyaustin Newbie

    Joined:
    Aug 27, 2013
    Messages:
    32
    Likes Received:
    24
    Occupation:
    Web Developer
    Location:
    Ireland
    Main Method[HR][/HR]


    Welcome back to Buckyaustin's Java tutorial. In this post I will be discussing how all your main methods should look and how to achieve it. I will be showing you a few more methods.

    How should your main method look?

    Your main method should only be about ten lines of code. That seems like nothing if you look back at all the versions you have done before. You couldn't do much with just ten lines? Good point, but what if the ten lines called ten methods, and each of those methods had one thousand lines of code? Well that's ten thousand lines of code, which can do quite a lot.

    What is the reason for the ten lines?

    The reason for this is when you think of how a program should work you can summarize it into about ten lines, no matter how complex it really is. The methods go into the fine details.

    Is there an advantage to this?

    Yes, you code out your main method once and never have to look at it again, ever. You look at what part of the program you want to change, check which method holds the code for that part, jump to that method and edit that method. Having everything broken up into methods saves time understanding the code and updating the code.

    OK I said I would show you how your program should look like, so copy Currencyconverterv4 and paste, call this one Currencyconverterv5. Update the block comment at the top.

    Code:
    public class CurrencyConverterV5 
    {//start of class[INDENT]static int choice = 0;
    [/INDENT]
    [INDENT]static Scanner keyboardIn = new Scanner(System.in);
    static double euroAmount = 0.0;
        
    public static void main(String[] args) 
    {//start of main method
    
    [/INDENT]
    [INDENT=2]do 
    {//start of do
    [/INDENT]
    [INDENT=3]    
    System.out.print("How much do you want convert? ");
    euroAmount = keyboardIn.nextDouble();
    setMenu();
    choice = keyboardIn.nextInt();
    checkRange(1, 4);
    calcConversion();
       
    [/INDENT]
    [INDENT=2]}while(choice != 4); //end of do while loop.[/INDENT]
    [INDENT]   
    [/INDENT]
    [INDENT]}//end of main method
        
    //checks the range and if outside the range asks the user to re-enter
    public static void checkRange(int min, int max)
    
    {//start of checkrange
    [/INDENT]
    [INDENT=2] if(choice < min || choice > max)
    {//start of if
    [/INDENT]
    [INDENT=3]System.out.println("Please enter a valid choice.");
    choice = keyboardIn.nextInt();
    [/INDENT]
    [INDENT=2] }//end of if
    [/INDENT]
    [INDENT]}//end of checkrange
        
    //Your main method is meant to only be 10 lines at most. So lets achieve that.
    
    public static void setMenu()
    {//start of setMenu
    [/INDENT]
    [INDENT=2]System.out.println("\t\t Currency Converter!");
    [/INDENT]
    [INDENT=2]//Display the menu for the user to choose from.
    System.out.print("1: \t Convert to US Dollar." +[/INDENT]
    [INDENT=4]            "2: \t Convert to AUS Dollar." +
    [/INDENT]
    [INDENT=5]    "3: \t Convert to STG. \n");
    [/INDENT]
    [INDENT]}//end of setMenu
        
    [/INDENT]
    [INDENT]public static void calcConversion()
    [/INDENT]
    [INDENT]{//start of calcConversion
    [/INDENT]
    [INDENT=2] switch (choice) 
    {//start of switch
    [/INDENT]
    [INDENT=3] case 1:    System.out.println("$" + euroAmount * 1.35 + " is the US Dollar conversion.");
    break;
    case 2: System.out.println("$" + euroAmount * 1.44 + " is the Aus Dollar conversion.");
    break;
    case 3: System.out.println("£" + euroAmount * 0.84 + " is the Sterling conversion.");
    break;
    case 4: System.out.println("Exiting program.");
    break;
    default:System.out.println("Invalid Choice made");
    break;
    [/INDENT]
    [INDENT=2] }//end of switch
    [/INDENT]
    [INDENT] }//end of calcConversion
    [/INDENT]
    }//end of class
    
     
    
     

    breakdown;


    There is nothing really new in this program, just that a few lines of code have been removed and new methods created to replace them. Basically they do the same thing.
    Notice the main method has a do loop and a few lines that just describe what we wanted the program to do in the first place?
    The hardest thing to do here is to decide how many methods you should have, what each method should do and what the methods should be named. The names need to describe what the method does, that is how our main is just a description of what the program should do.

    As I said in the last post, we will be taking a break from code, but don't get too relaxed. We will be moving onto the world of pseudo code, test plan and test logs.
     
    • Thanks Thanks x 1
  20. pxoxrxn

    pxoxrxn Supreme Member

    Joined:
    Dec 21, 2011
    Messages:
    1,397
    Likes Received:
    2,066
    Buckyaustin are you thenewboston?