Welcome, Guest: Register On Nairaland / LOGIN! / Trending / Recent / NewStats: 3,151,566 members, 7,812,830 topics. Date: Monday, 29 April 2024 at 08:13 PM |
Nairaland Forum / Nnasino's Profile / Nnasino's Posts
(1) (2) (3) (4) (5) (6) (7) (8) (9) (10) (11) (of 15 pages)
Technology Market / Re: Is Jumia Nigeria's Black Friday A Comercial Scam? by nnasino(m): 2:25pm On Dec 01, 2014 |
Same with me, the rechargeable fan i've been monitoring at 7 thousand something suddenly became 9300 while the discounted price was still the 7 thousand something. |
Programming / Re: Java Tutorial For Beginners by nnasino(m): 2:09pm On Dec 01, 2014 |
choose4me:It's alright as long as you learn. You can achieve this using apache's fraction class. visit http://commons.apache.org/math/userguide/fraction.html. |
Programming / Re: Java Tutorial For Beginners by nnasino(m): 1:01pm On Dec 01, 2014 |
Access Specifiers Access specifiers are used to specify which classes can access resources (variables/methods). There are four access specifiers in java. public, private, protected and default default The specifier we have been using the default specifier (not writing anything before a variable/method). The default specifier means that only other classes from the same package can access the resource. Packages will be explained later on and the default access specifier will be revisited. private/public If a resource is specified as private it can only be accessed by members of the same class. If a resource/member is specified as public then it can be accessed by all classes. In our class code:
With the above code, then mth101Object.creditLoad;will fail, now we have to use the public method mth101.object.getCreditLoad(). We will discuss protected much later, but you can read it up if curious. static The static keyword is used to specify that a member belongs to a class and not an object. For example, in our above code, we have no static variable. This is because all the members we have defined all belong to objects. The course framework can not have a course title, only a tangible object (a real course) can have a course title and a course credit load. You can think of static members as members that each object doesn't have its own unique copy. A member that has a single copy for all objects created i.e a member that belongs to the class. In the Course class, let us think and come up with a static variable. A variable that can belong to the Course class only. I've got it. We usually check the credit load that passed into the setCreditLoad method to see if it is greater than 20. We hard coded this value 20 into our code. This isn't good practice, instead we can create a variable MAXIMUM_CREDITLOAD. But this information is more to the framework (class) than to individual objects (it's the same value and storing it in each object will be a waste of space). So, we use the static keyword to attach it to the class and not to the objects that are created.
package In java, a package is simply a way of grouping similar classes together. The package of a file specified on the first line of the file using the syntax package nameOfPackage;. All classes declared within that file will belong to that package. Packages are synonymous with folder names. An example of the usefulness of packages is when creating a desktop application. For instance, this our GPA program; say we want to create a GUI for it, we can put the GUI in a package named gui, and for our classes which form the core of the application we can put them in a package named core. If we don't specify a package name in a file, the classes in that file will be added to the default package. Now, we understand packages we can now revisit the default access specifier: say we have project structured like this: GPAgui ----core --------Course ------------int creditLoad; ------------private String courseTitle; --------Student ------------private int numberOfCourses; ------------public int studentName; ----gui --------MainWindow ------------.....////. ------------../gui stuff//// From the above: default: creditLoadis default therefore members within course can access it, Student can also access it since they are both in the core package but MainWindow can not access it. public: studentName is public therefore MainWindow, Course and Student can access it private: courseTitle Only members of Course can access courseTitle That's all for today, try and digest the message for today. Tomorrow, we will use the knowledge we have acquired to make our program better. Cheers, |
Programming / Re: Java Tutorial For Beginners by nnasino(m): 12:11pm On Dec 01, 2014 |
With the class defined, we can now create objects with it. Objects are like variables but they are a bit different. A variable is stores the data it holds whereas an object stores a reference to the data it holds. Don't bother yourself with this for now. To create an object, we create its reference ( a name that will point to it) and then initialize it with an object (the real data).
Using Objects Objects are used with the '.' notation. That is if we have an object mth101Object. We can do the following:
This way we can use an object just like a variable. We will now introduce a few more new concepts. Constructors Access Specifiers static package Constructors A constructor is simply a special method that is called when an object is to be created. In the above example, we wrote new Course(). The Course() method is the constructor. But we didn't declare any method like that in our class. Java creates a default constructor if we don't define any constructor. Notice that the constructor used above doesn't take any arguments. This is not a must. Like any other method, a constructor can take any number or types of arguments. Now, we will improve our course class code by adding two constructors. The compiler chooses which compiler to call depending on the parameters passed to it. This is called method overloading and will be discussed later on. Code for defining a constructor: public NameOfClass(parameters){ Now, we will create two constructors for the class, one will take no parameters and the other will take 2 parameters, the course title and the credit load of the course.
We can therefore create Course objects as follows:
|
Programming / Re: Java Tutorial For Beginners by nnasino(m): 11:04am On Dec 01, 2014 |
Hello, everyone, Today i'll be introducing classes and objects. I'll take this slowly so we can get the grasp of it. We will then use them to improve our GPA application. Classes: A class is simply a framework for creating objects. A class is a description of something. With this description that 'something' can then be created. For example, in our above program, we can have a class named course. Classes describe objects. The description can include properties and behaviours. Properties are simply variables that are embedded in the class. For example, a property of a course is the course title, it's credit load and probably the level it is for (300 level, 400 level etc). Behaviours are methods/functions embedded in the class. An example of a behaviour of a class is for instance setGradeLetter(). Now, we can simply set the grade letter for the course by setting the property but then a method is better because with a method we can check the letter that was inputted to see if it is between A to F. We could also set the score after setting the grade within the same function. So, in a nutshell - A class is a framework used to group related data which represent an entity together. This framework can then be used to create objects. - An object can have properties and behaviours which are variables and methods respectively. To define a class, we use the following syntax:
For instance, a course class can be declared as follows:
|
Nairaland / General / Re: My Experience With Racists. by nnasino(m): 2:20pm On Nov 30, 2014 |
quantumphysics:thanks |
Nairaland / General / Re: My Experience With Racists. by nnasino(m): 2:01pm On Nov 30, 2014 |
SirShymex:what's. FOB? |
Programming / Re: Java Tutorial For Beginners by nnasino(m): 5:53pm On Nov 28, 2014 |
Hi, everyone. I'm back for today's lesson. Today we will add some improvements to the GPA program of yesterday while introducing some new concepts. Looking at our program closely we can easily see that there are problems with it. There isn't any reasonable error handling. The smallest of errors from the user can cause the program to crash or to behave wrongly. For example, if in place of credit load, the user enters a letter or a word, the program crashes with an error. Also, if one enters a number or a letter that isn't between A and F, then the program just treats it as zero. So today, we will be correcting all those issues and thus improving our program. We will be looking at error handling today. Also called Exception Handling. Exception handling is simply a way of handling an error thus stopping it from crashing the application. In java, when an error occurs, an exception is thrown, if it is not handled, then it crashes the program. Handling an exception is referred to as catching it. So in java when an exception occurs, we can either handle it or 'rethrow' to another part of the application. This part can also either handle or rethrow it again. This can go on till the last part where if it is not handled it causes the program to crash. There are a few constructs/keywords used in exception handling. They include:
I won't explain them in words, rather i will use them in our program. Basically, to catch an exception, we put the piece of code that can throw such an exception within a try...catchblock as follows:
Now, looking at our code we can see at this point, we need some exception handling:
The bolded line can potentially throw an exception. You can verify this by inputting a letter instead of a number when asked for credit load. We can put this in a try...catchblock but then what would we put as the exception handling code? and how can recover back to where the code stopped?. We can achieve this by putting this code into its own function/method. So we create a function called readCreditLoad() which we can call that will handle its exception handling independently and will only return after a valid credit load has been inputted. So here is the function:
If we now replace the previous line with our function we get a better more robust program:
Now that the credit load part is corrected, let us correct the grade letter part. We will do this by modifying the getGradeValue() function. We will make it read the grade by itself and handle exceptions itself also.
This is the full code:
So, today we learnt about exceptions and how to use them to make our programs more robust. Try and practise this on your own. Are there any improvements that can be made? Try and use exception handling when reading the number of courses and number of years. |
Technology Market / Re: Watchout For Jumia n Konga Black Friday Scams by nnasino(m): 2:02pm On Nov 28, 2014 |
I ordered something today on konga, i'll give an update later on. But my brother said its legit. Konga warehouse is opposite his office and some of his colleagues bought stuff yesterday. He encouraged me to go on. I'll post the outcome later on. |
Programming / Re: Java Tutorial For Beginners by nnasino(m): 1:10pm On Nov 27, 2014 |
Wow, good day everyone it's been awhile been pretty busy with work. Today, we'll take on a common problem which will help us revise all we have learnt so far and introduce a few new constructs. We will create a program that will calculate the CGPA of a student. It's a pretty simple program but it helps reinforce all we have learnt so far. First of all, calculating cgpa involves the following: - get the number of years to calculate - for all the years - for all the semesters get the number of courses offered for all the courses - get the title/code of the course - get the credit load/unit of the course - get the letter grade obtained calculate Total number of units and total grade point of the semester - add all TNUs of all semesters (Total number of units) - add all TGPs of all semesters (Total grade point) - CGPA = Total TGP / Total TNU - Display the CGPA to the user We now have the algorithm let's now take each part one at a time: But first let us declare variables we will be needing:
- get the number of years to calculate To get any input from the user we need the scanner class so initialize it first before reading the number of years.
- for all the years From the statement we can deduce that we will use a for loop for this.
- for all the semesters Note that this is within the years for loop
get the number of courses offered for all the courses - get the title/code of the course - get the credit load/unit of the course - get the letter grade obtained -calculate Total number of units and total grade point of the semester This is nested in the semesters for loop
We can see that we used the function gradeValue(gradeLetter) and therefore we have to define it. The function takes the letter grade entered and returns the equivalent value. A is 5, B is 4, C is 3, D is 2, E is 1 and F is 0. We can achieve this using a switchstatement.
You can see we have done something different here. You can have more than one case run the same piece of code. Above, if the enters a small a or a capital A it returns 5. Also, we didn't use breaks in the switch because return exits the loop so no need for breaking. Put this above the main (public static void main()) method. - add all TNUs of all semesters (Total number of units) - add all TGPs of all semesters (Total grade point) This is done within the yearsfor loop
- CGPA = Total TGP / Total TNU - Display the CGPA to the user
Combining the code together we have:
Type this into a file named GPA.java and compile and run. We will build on this file while introducing new concepts in later lessons. Well, have a nice day everyone and happy coding. |
Programming / Re: Java Tutorial For Beginners by nnasino(m): 2:28pm On Nov 22, 2014 |
Methods Methods are used to group a set of statements performing one task. When you write code which you notice keeps repeating itself then you might need to create a method/function to handle that task. Functions can take values called parameters which it will use in its computation. An example of a function is a function that checks if a number is a prime number or not. Functions/methods can return an answer or not. When a function does not return any value it is of type void. Defining a function:
If you are not returning any value then type should be void. If you are returning a value then type should be the type of the value you want to return (int, float, double, String etc). Also, if you are returning a value then you must have the return keyword in the body of the method. The parameter list, is a comma separated list of the parameters to be passed to the function. The parameters must have the type and the name by which they will be accessed. An example
The above function takes, two Getting user input from the user: We haven't discussed classes or objects so far but we will need to use them in our exercises so i'll give crash course on both. A class is simply a framework for creating objects. It contains variables and functions within it which represent properties and behaviours of the objects it will be used to create respectively. For example, a vehicle class is a framework for creating vehicles. It's properties can include speed, colour, size, etc while it's behaviours include move(), stop(), changeOil() etc. So with a single class definition we can create numerous objects each having their own properties. The good thing about objects is that we can use them without knowing how they are implemented. A car can be driven without knowing what engine is in it or how it was built. Objects can also be nested within one another. A steering wheel is a fully developed object with its own components. But it is contained in the vehicle object. The vehicle doesn't need to know anything about how the steering wheel was built/created all it needs to know are what it can be used for and how to use it. We will delve into objects later on but for now we need to use one in our program ( we will be using it regularly). The Scannerclass is a built-in java class for reading input. It can read from files, standard input (user) and other streams. To use these functions we need to create an object of the Scanner class. In java this is done by: Scanner scannerObject; We have declared the scanner class, but before we can use it we need to initialize it. New Concept: Constructor: A constructor is a function that is used to initialize a newly created object. We'll stop there for now and continue. Just note that the constructor of a class is a function with the same name as the class. Now the Scannerclass's constructor takes one parameter which represents where the input comes from. In our case, the input comes from Standard input (keyboard), so the parameter is System.in. So to declare and initialize the Scanner object we have:
This creates an object for us. We also need to import the Scanner class. We do this by putting import java.util.Scanner;at the top of the file. For now ignore all these, we will still treat objects and classes later on. But for now just copy this code into your file. Note: If you use netbeans, set up your key map with the eclipse settings so you can follow with the shortcut keys i will be using to do this, click Tools menu > options, then click the keymap tab and change the netbeans to eclipse, click apply and then ok. Netbeans will be very helpful when working with objects. Now you have set up your key map. You can use the following: Type Sca and press Ctrl+space, this will bring up a list of all classes matching the what you've typed select the one you require and press enter, in this our case the one in java.util. Doing this will automatically import the class for us. Also, we can type Scanner and declare and initialize the object without importing. The IDE will definitely complain, at this point press Ctrl+shift+O, this imports all missing classes. As we move on, i'll be introducing more function keys for making our work easy. Now to our challenges: Challenge 1: Write a program which displays the number of prime numbers from zero to a number. Number should be provided by the user. We break the problem into components: - Get number from the user. - check if each number is a prime number. if they are increment the count. - Display the count to the user. To get input from the user we use the Scanner class -We will be checking many numbers therefore we will need a loop -We will be checking if a number is prime so we will create a function to check The program therefore goes:
|
Programming / Re: Java Tutorial For Beginners by nnasino(m): 12:15pm On Nov 22, 2014 |
Let's take a deeper look into the for loop. for(initialization; condition; iteration) Note that all/any of initialization, condition or iteration can be left empty but make sure the semi colons are left. For example, you can have a for loop like this for(;, this is simply an infinite loop. Now let us take the components one by one: Initialization: As we said earlier to initialize a variable is to give it a value. This part of the for loop is used to set the value of a variable. You can set the value of multiple variables here. You can also declare variables here. Most of the time you will declare a single variable called the loop control variable. The loop control variable is the variable used to control the execution of the for loop. It is usually part of the condition and part of the iteration. Example: for(int i =0; i < 4; i++) In the above code, the loop control variable is i. It is initialized to the value 0. You can also see that it is part of the condition (i < 4) for ending the loop. It is also part of the iteration as it is incremented at each point. Remember that you can declare more than one variable in the initialization part. For example, in this snippet for(int i = 0; i < object.size(); i++), if the size of object is lets say 2000, this means that object.size() will be called 2000 times. This is a waste of processing power since object.size() remains the same throughout the execution of the for loop. We can store the size of object in the initialization and refer to the variable instead of calling the function all the time. for(int i =0, size = object.size(); i < size; i++). This save us processing power at the expense of creating a variable (memory). This shows that there will always be a tradeoff between processing speed(power) and memory. So we should be able to weigh the benefits and choose when using extra memory will be advantageous to our processing. Condition This is checked at each iteration to know whether the loop continues. It the condition evaluates to true, the loop proceeds, but if it is false then the loop exits. Note that any expression that evaluates to true or false can be used here. examples:
Iteration This part is simply to insert code that you want to execute at the end of each iteration. For example increment the loop control variable i++ or basically anything else. But it is advisable and good coding practice to only put code which affects the loop control variable here. examples:
One more thing before we conclude: [b]break, continue and labels[\b] A breakexits the loop it is contained in. A continueskips all the code ahead and moves to the beginning of the loop and labels are used to specify which loop to apply these constructs on. e.g
In the snippet above, the condition for the loop is truetherefore it is an infinite loop. Sometimes infinite loops are necessary so we need a way to break out of the loop. This is where we use the breakkeyword. In the snippet above, the loop runs until someThing evaluates to true. For continue, it is used to skip all code and return to the beginning of the loop. example:
In the above snippet, if someThing evaluates to true, statement 3, 4 and 5 are skipped and execution continues at the beginning of the loop that is i <5 is checked. labels: labels are useful in loops are nested. A loop is said to be nested if it is located inside another loop. For example:
In the above code snippet, the inner for loop is broken out of. But say we wanted to break out of the outer for loop? this is where labels come in. We can give loops labels, which will then be used together with the break and continue statements. To break out of the outer loop in the above code snippet, we write as follows:
Well, that's all for loops, and we are done with part one of the tutorial. We now have all we need to solve most problems that can come up. We will now start solving problems to strengthen our knowledge. This is the fun part, and I will like for it to be interactive. |
Programming / Re: Java Tutorial For Beginners by nnasino(m): 5:08pm On Nov 21, 2014 |
Hello, everyone Welcome to today's lesson This is the last in the first half of this tutorial. Today we will be treating [bold]Loops[/bold]. If we complete this lesson then we will be ready to solve most problems. The loops are as follows: 1. whileloop Now, as i said earlier on in this course, Loops are simply a mechanism for making the computer repeat a task. 2. do whileloop 3. forloop We also have the switchstatement. I will treat all of these one after the other. 1. whileloop: The while loop is of the form:
the while allows us repeat statementuntil condition == false. Note that if there are more than one statement then you need to use curly braces to group these statements together. i.e
2. Do whileloop does basically the same thing with the while loop. It is of the form
The do while literally means do "statement" until condition == false. The difference between the do while loop and the while loop is that the statement is executed at least once in a do while loop whereas it might not get to be executed in a while loop if the condition fails from the onset. The do while loop isn't widely used. 3. for loop: the for loop is of the form :
In a for loop, there is the loop control variable. Finally we have the switch statement. It is of the form
The switch statement is basically a better way of using if else statements. Instead of using if else statements we just specify the possible values and the statements that should be executed if they are encountered. With the constructs we have learned so far, we can now comfortably call ourselves programmers. Well, we can if we have mastered these constructs and know how to use them solve problems. I will now give examples: while
the above code snippet displays the square of the first ten integers. This can be converted into a for loop as follows:
I'll be back later for the continuation of this lesson. 1 Like 1 Share |
Programming / Re: Java Tutorial For Beginners by nnasino(m): 2:27pm On Nov 21, 2014 |
mgb4reel:Thanks boss, for the answer |
Programming / Re: Java Tutorial For Beginners by nnasino(m): 6:02pm On Nov 20, 2014 |
JAGZZ:I don't really understand your question. Do you mean to sum the first ten integers? If so then this will work:
If you just want to sum ten arbitrary integers then simply add them using +. Hope this helps |
Politics / Re: Happy 57th Birthday to President Goodluck Jonathan! Drop Your Wishes for Him by nnasino(m): 8:45am On Nov 20, 2014 |
Happy birthday, mr president llnp 2 Likes |
Technology Market / Re: Scuit: Shop & Ship From China, USA, Dubai & UK (Express, Cargo & Shipping) by nnasino(m): 2:34pm On Nov 18, 2014 |
BizBloke:Alright, thanks 1 Like |
Technology Market / Re: Scuit: Shop & Ship From China, USA, Dubai & UK (Express, Cargo & Shipping) by nnasino(m): 2:30pm On Nov 18, 2014 |
BizBloke:Sorry, but this is a bit on the high side. So i'll let it slide. The cost of bringing it to nigeria outweighs the cost of the items themselves. |
Programming / Re: Java Tutorial For Beginners by nnasino(m): 4:59pm On Nov 17, 2014 |
Hello guys, Welcome back Last time we talked about variables. We agreed that variables are named storage locations which can be read and written to. They are simply ways we can use to remember data that we need in the future. Computers nowadays have so much memory that the possibilities are endless. Today, we will talking about conditionals and booleans First of all, a boolean as stated earlier is an expression or variable that evaluates to true or false. For example, true, false, 3 > 3, 4 < 8 etc. Generally, any expression that evaluates into true or false is a boolean. Now, a conditional is a construct that controls program flow based on the value of a boolean. For example,
So booleans are very useful in programming. We have learnt so far that the computer can store information and variables and now we've learnt that the computer can check a condition to decide what it will do next. This is extremely important. With this we can create more powerful programs. But let us look into booleans a little more. A boolean expression is made up of one or more boolean operands and one or more boolean operators. Examples include :
All of the above are boolean expressions. They simply evaluate into true or false. If i type if(true)it will execute whatever comes next since the condition or boolean is true. Also, if i have a variable boolean isReady = true;and i type if(isReady)the condition will also pass. Now, looking at the conditional / boolean operations: < - less than > - greater than >= - greater than or equal to <= - less than or equal to == - this checks equality. this is different from =, which is used to assign != - this checks for inequality. that is if you write 8 != 9, it will evaluate to true. Now, just as in arithmetic expressions we can create compound expressions such as (23+43) -((3+33)-9), we can also combine booleans expressions to make more complex expressions. The operators are called the Logical operators. They are AND, OR, and NOT. AND = If you have money and you can read -- go to school.. This means that if all the conditions are correct then true will be returned else false is returned. OR = if you can play football or you can fight taekwondo -- come to the stadium. This means that if at least one condition is met then it returns true. NOT = If you are not up to the age of 18 --don't come to the bar This is used to get the opposite of a boolean. If you have true and you NOT it, then you get false and vice versa. the symbols for them are: AND = && OR =|| NOT = ! With these tools, we can now make some more complex applications. Let us write a program that solves a quadratic equation. A quadratic equation is of the form ax2+bx +c. The formula for solving it is (-b +- sqrt(b2 - 4ac) )/ 2. all First of all, before solving we have to decide how we intend to solve it. AlgorithmQuadratic(a,b,c): read a, b,c With this algorithm we can then write our program
That's all for now. Try and digest the message for today. Remember, the way to solve a problem is thinking about it first before writing code. Have a good evening everyone. Cheers 4 Likes 1 Share |
Technology Market / Re: Scuit: Shop & Ship From China, USA, Dubai & UK (Express, Cargo & Shipping) by nnasino(m): 4:27pm On Nov 17, 2014 |
Hello bizbloke, Please i want to purchase these items: they are clothes i don't know how their service is priced but i hope its reasonable and affordable: http://www.ebay.com/itm/Theres-no-place-like-127-0-0-1-programmer-home-coding-127-IT-gift-tee-t-shirt-/321248602878 and http://www.ebay.com/itm/WRESTLING-ARMBANDS-BLUE-BLACK-W-JEFF-HARDY-PICTURE-TNA-WWE/281446513099?_trksid=p2047675.c100005.m1851&_trkparms=aid%3D222007%26algo%3DSIC.MBE%26ao%3D1%26asc%3D27538%26meid%3D2f99ce945ca241688dbec5696e9b997a%26pid%3D100005%26prg%3D11353%26rk%3D1%26rkt%3D6%26sd%3D271575113859&rt=nc Help me with the quote. Thanks |
Programming / Re: Java Tutorial For Beginners by nnasino(m): 6:41am On Nov 17, 2014 |
sconp:This is perfectly correct. But add the two closing braces for main and the class }}. |
Programming / Re: Java Tutorial For Beginners by nnasino(m): 11:01pm On Nov 16, 2014 |
sconp:Nice one bro, just keep yourself motivated and you'll be unstoppable. I'll appreciate your feedback on the simple interest app and if you have any questions I'm here. Cheers |
Programming / Re: Java Tutorial For Beginners by nnasino(m): 2:25pm On Nov 16, 2014 |
mgb4reel:Yes bro, your experience will be highly appreciated, thanks |
Programming / Re: Java Tutorial For Beginners by nnasino(m): 2:24pm On Nov 16, 2014 |
basbone:Well, I think that was wrong of the Java designers and this is usually noted by many Java books. I think Java isn't really cut out for console application development. Also, apps that read input from standard input at runtime are quite rare nowadays. Also, it's not too tough reading from Java console input . C# is developed by Microsoft and basically built it based on Java so definitely they had time to examine java's flaws and make improvements. |
Programming / Re: Java Tutorial For Beginners by nnasino(m): 11:03am On Nov 14, 2014 |
Now, we have enough knowledge to move on. Variables Many people say the computer is very powerful but why exactly is it powerful? If you as a human being were told to sit down and just simply do the following 200 times: - Add 1 + 1 write the answer 2 on a piece of paper - 1st time - Add 2+2 write the answer 4 on a piece of paper - 2nd time - Add 4+4 write the answer 8 on a piece of paper - 3rd time - - - Add ............................................................... 200th time Now, not many people might be able to do this to the end. You might get a headache, get frustrated, get tired, or simply refuse to continue the job. Why because this work is repetitive and tiring and not fun. But the computer, on the contrary is well suited for these kinds of jobs because not much thinking is required and the computer can work without getting tired. The simple sentence is "as long as you can specify to the computer what to do, It will do it without any problem". If for example we were told to do the job above, we would need to basic components. We would need to process ( 2+2, 1+1, 4+4 etc) and we would need to store (write 4 on a piece of paper). We would need a lot of paper to store the answers of the processing but the computer has more than enough space to store this information. Now, a small part of the piece of paper where a result is written and can be retrieved is analogous/like a variable. A variable is simply a named location were information can be stored and later retrieved. On the piece of paper, if we don't arrange the results we wrote down well, we might find it difficult reading them later. This problem is eliminated in a computer as a variable in a computer has a name. So the first result can be named result1and whenever we need it we just write result1 and we get the data. As a human being, even a genius, if you were told to store 25 sixdigit numbers in your head for an hour along with names that identify each number uniquely and say a number whenever it is requested for, this would be very difficult. But the computer, can store a millions of such numbers and retrieve them easily in a fraction of a millisecond. This is one of the features of the computer that makes it a powerful machine. Now, as i said earlier and i'll keep emphasizing, when confronted with a problem sit down first with your pen and paper and think about the problems. Now, we have introduced variables, you should think about the variables that you will need. The information that you would need to keep track of to solve the problem. In the above problem, we are to add 1 + 1which gives us 2. We then add 2 + 2which gives us 4. We then add 4+4which gives us 8. At the moment, we will just do for three times since we don't yet have enough programming knowledge to solve a larger problem. Looking at this problem, we can see that the result of each operation is used in the next operation. Which means we should keep track of the result. Therefore a variable is needed. Java, is a strongly typed programming language. This means that every variables' type must be known before it can be used. The compiler needs to know so that it can know how much space to allocate to the variable. For example, on your piece of paper, if you want to store a small number of like 4 digits, you use a small square but if you want to draw a picture you use a larger square. Using the type of the variable java decides how much space to allocate for a variable. There are various types in java but they are divided into two types: primitive and reference types. We will discuss only primitives here: Primitive types are the default data types on which all other types are built upon. They are keywords and therefore should be written with all lowercase. The primitives include: Keyword - Description int - Integer, this is used for saving whole numbers e.g 1, 2, 23424234, -3423423, 0 float - Floating point number, this is simply for saving fractional numbers , 1.4334, 1.5e24, 3.14, -3214.323 double - double precision floating point number, this is the same with the float but it stores with a higher precision. More space is used by the computer to store the a double. e.g 1.34, 324.52, 23.35432, 534.32342 char - Character - this represents a single character e.g 'A', 'b' , '1', '[' etc Please note that single quotes must be used. byte - this is an int that can hold 8 bits of numbers. It is simply a small int that represents a byte. short - this is an int but it has a smaller capacity than the normal int. long - this is an int but it has a larger capacity than the normal int. boolean - these variables can take two values: true or false. They are extremely important to programming void - this is simply void. this is the void type used when nothing is required. (explanation will come later) If you are interested in knowing the space used by each of these types, visit http://www.idevelopment.info/data/Programming/java/miscellaneous_java/Java_Primitive_Types.html . To use a variable, we must tell the compiler its type and its name so it can allocate space for it. This is done by typing the type of the variable, a space and then the desired variable name. e.g int integerNumber; This is called Variable Declaration. After a declaring a variable, you can then assign values to it. This is done by using the = operator. integerNumber = 20;. The first time you assign a value to a newly created variable, you are initializing it. You can declare and initialize a variable on the same line like this int integerNumber = 20;. This is good practice. Always initialize a newly created variable with a default value. For integers, use 0, for floats/doubles use 0.0, for booleans use false etc. Now, we can use variables lets solve our earlier problem. to remind you, we were supposed to add 1+1 print the result 2, add 2+2 print the result 4, and finally add 4+4 print the result 8. We said we needed to store the result so we declare and initialize the variable. int result = 1; Our final program should be:
I'll like to explain line 3, it simply means get the value in result and add it to the value in result. Then assign the result of the processing to result again. These sort of expressions are common in java, so don't be confused. Finally, for this lesson, i will introduce the arithmetic operators. They are +, -, /, *, %, =. + is for adding two numbers (floats, ints ,doubles etc), - for subtracting numbers, / for dividing numbers - note that when an integer is divided by another integer, if there is a remainder it is truncated (thrown away). This means that 5/2 = 2 not 2.5. If you required the fractional part, then one of the operands should be a float or a double. You can do this by multiply by 1.0. That is 5 / 2 * 1.0 = 2.5. * is multiplication. % - this is the modulus operator. It is not very common but is very important. it is used to find the remainder in a division. It is only used on integers. 5 % 2 is 1. That is the remainder is 1. It can also be used to make convert numbers into a range. For example, to convert any number to the range 0 to 25, simply apply the number % 26. = this is used to assign values to variables. Note that a variable must always be on the left hand side. Numbers/literals can not be on the left hand side. Exercises: - Rewrite our first program to print Hello yourname. But this time store your name in a Stringvariable named name. String is not a primitive variable but we can use for this example. To declare and use the a string variable write String name = "Justin";. Note the double quotes. Also, the + operator can be applied to Strings. What it does is to combine the two strings into one. So "Justin " + "Bieber" = "Justin Bieber".. Good luck. - Write a program to calculate simple interest. the formula for simple interest is simple interest = (principal * rate * time) /100. use variables extensively. We've come to the end of this lesson. Stay motivated everyone and remember i'm here to take any questions you have. Cheers!! 1 Like 1 Share |
Programming / Re: Java Tutorial For Beginners by nnasino(m): 9:18am On Nov 14, 2014 |
With what we have let us do some simple exercises to get us used to java syntax. 1. Write a program that prints My name is yourname. 2. Write a program that prints 1 + 1 = 2 3. Write a program that prints Java beginners course 4. Write a program that prints I am a hardcore java programmer 5. Write a program that prints all the things above in a single program. These programs can be done very easily by simply replacing the hello world in the first application with the text you want to print. Now, you've done this you are probably a bit comfortable with the syntax of java. You might have run into some problems while writing this code. The advantage of using netbeans as a beginner is that spotting your errors are much easier. Without netbeans you would need to write your code, then compile it before you can see the errors in your code. but with netbeans as you code you see the errors in realtime. Now, a common error you might see is "Symbol not found". Please note that java is case sensitive so nairaland is not equal to NairaLand or nAirALand even they are the same word but the some the characters are of different cases. Now, if you type system.out.println(""you will get an error because you typed system instead of System. Secondly, Alllines of code end with a semicolon ';'. ignore the lines that end with }. {} braces group linesof code together so they are not really lines of code therefore they don't need to be ended with a ;. With that in mind, how do we know when a word should start with small letters or capital letters. There are a set of words referred to as keywords in java. These are words reserved by the compiler to convey a special meaning. They all start with small letters. Examples of keywords include public, class, voidetc. Notice that they are all small letters. These are keywords and they can be differentiated from other words in netbeans by their colour. From the screenshot above, you can see some keywords in blue. Other keywords can also be seen in purple. Netbeans is highly customizable, meaning you can change the colour of categories of code to make them recognizable and more convenient for you. You can get the theme above from this link http://plugins.netbeans.org/plugin/55169/torti-dark-theme. Click the tools menu > options. Then click the fonts and colors icon. Click import at the bottom of the dialog and select the downloaded zip file gotten from the link and click ok. Now correct your errors and run your program. Did you get the required result? Good. 3 Likes |
Sports / Re: Congo Vs Nigeria: AFCON Qualifiers (0 - 2) ON 15th November 2014 by nnasino(m): 11:28am On Nov 13, 2014 |
I have a feeling that we will be at the nations cup. |
Programming / Re: Java Tutorial For Beginners by nnasino(m): 10:24am On Nov 13, 2014 |
Now, we will build our first application. The hello world application:
Explaining line by line: Line 1: Java is an object oriented programming language so whatever we do MUST involve classes. We will understand classes later on but for now we will just ignore that line. Whenever creating a new file just put in your class NameOfClass and your good to go. By convention class names start with capital letter. Line 2: public static void main(String[] args){; we will also ignore this line as we don't know enough as at now to understand it. Just know that the program starts its execution from this point. So whatever code you want to execute for now has to be between the two { } braces. Line 3: This line is a comment. A comment is a part of your code which is not executed by the compiler. They are there to explain and describe your code. Comments are very important. When you leave a piece of code for three months and come back to it, you will realize that without comments it might be impossible to understand exactly what is going on. Java has three kinds of comments but for now i'll explain two. The single line comment and the double line comment. The single line comment is the type we used it done using two consecutive // characters. It makes every other character after the // till the end of the line a comment. the second is the multi line comment. It spans over multiple lines and is started with a /*and ends with a */ Line 4: This prints or displays 'Hello World' to the user Line 5: End of the public static void main. Line 6: End of the HelloWorld class. {} braces are used to group pieces of code together. That's all for now. Everyone should setup their environments (netbeans, jdk). I will be taking any questions you have on setting up and the lessons so far. If you are done setting up, see if you can modify the program to display Hello Your Name instead Hello World. Remember shift f6 to run. Cheers. 3 Likes 3 Shares |
Programming / Re: Java Tutorial For Beginners by nnasino(m): 9:47am On Nov 13, 2014 |
Lesson 1 Algorithms introduction: Now, a programming language is just what it is a language. One can have a dictionary of a language say french and know many words but if you don't know how to use these words to make sense and communicate then it is useless. This analogy applies to programming also you may know all the syntax of a language (if else , switch etc) but yet be unable to solve even the simplest of problems because on their own programming languages don't have any power. The power behind programming is; well you guessed it algorithms. An algorithm is simply a clearly stated way of solving a problem. Computers don't have any sense of their own so they only do exactly what you tell them to do. Lets say you want to buy airtime from a shop opposite your house. Now this is a problem. If you tell a human being, he/she can easily buy the airtime because of their intuition. But a computer doesn't have intuition. So let's assume you have a smart robot (imagine) and you wanted it to buy the airtime. You can't speak to it, you have to program it and it has only a basic set of operations. This is where you need an algorithm. We assume your robot computer has 6 basic operations: move- which allows you specify the direction and/or how many metres to move. stop- allows you to stop the robot at anytime message- allows you to display a message to on its screen (monitor) give- expel a tray from its body receive- take the tray back into its body. Now you have 6 basic operations or words in the programming language of the robot. But knowing that is not enough. The power in programming is being able to think and devise a means to combine these few operations to do reasonable work. This brings us to the design and implementation of algorithms. Now we will solve this problem: First, the airtime shop is opposite my house. So we keep the robot outside the house and . We make some assumptions in this problem. The shop is 10 metres away, the airtime seller isn't afraid of robots and is ok doing business with the robot. The seller also will not cheat the robot. The program starts as such : receive(N200)--We give the robot the money for the airtime move(North, 10metres)--Robot moves 10 metres toward the shop message("I want to buy airtime 200 etisalat" give(N200) receiver(Etisalat card)--The honest airtime seller then takes the 200 and puts in a valid etisalat airtime in the tray message("Thank you" move(South, 11Metres)--We move more than 10 metres so the robot hits the door and we know he is back Voila, we have our airtime. Now, if we were unable to devise a way to solve the problem using these small set of operations we would have ended up walking down ourselves to buy that airtime (wasting our time which could be used for playing pes ). Also, if the shop was 100 metres away we would just need to change the 10 metres to 100 metres. this illustrates that once a small problem is solved with a computer, it isn't that difficult to solve a bigger type of the problem. Final note: Algorithms are very important. Algorithms are referred to as a technology because with a bad algorithm it might take a super computer 10 years to solve a problem, but with a better algorithm the same problem could take a second on the same super computer. This is not an algorithms class but i'll try and chip in some concepts along the way. If possible, you can take an algorithms course. But most of all, when presented with a problem, have your pen and paper. Write out how you intend to solve the problem in clear steps first without writing even a single line of code. If you keep that discipline, you will find programming much easier for you. 8 Likes |
Programming / Java Tutorial For Beginners by nnasino(m): 9:19am On Nov 13, 2014 |
Hi, everyone. I was inspired by my friend and oga ezechinwa to start this thread. I will be teaching java to beginners in the house. I am not an expert but i think some knowledge can be shared. Tools needed are jdk (java development kit), netbeans IDE and a good computer. For jdk visit http://www.oracle.com/technetwork/java/javase/downloads/index.html Note: please install jdk separately, do not download the jdk + netbeans bundle For netbeans visit https://netbeans.org/downloads/ For a good computer, well visit computer village or jumia.com or if you already have one move on. Once, you have these installed, launch netbeans. Create a new project by clicking File Menu > New Project. Set up the required information and click finish. Once you have a new project you can then run the file you are working on by using the shortcut Shift+f6. You are now set and ready to take your first step as a java programmer. I will encourage you to persevere, that programming is fun, stimulative to the brain, and is rewarding. The important thing is not how much or how fast you learn but how long you can keep your attention to it. With time, you will forget the beginning days. Finally, before we start off, i will recommend that as a programmer you learn how to type. Yes, i mean it, learn how to type without looking at the keyboard. This will help you tremendously. Visit keybr.com for an online typing tool. If you can get yours hands on mavis beacon teaches typing that will also be fine and if you are from the linux world ktouch or klavaro will do. Thanks, and welcome aboard to the tutorial. 15 Likes 6 Shares |
Programming / Re: C++ Tutorial For Beginners... Part 1... by nnasino(m): 8:48am On Nov 13, 2014 |
badboy92:Thanks bro, I might start today or latest monday. 2 Likes 1 Share |
Programming / Re: C++ Tutorial For Beginners... Part 1... by nnasino(m): 12:08am On Nov 13, 2014 |
Ezechinwa:thanks, boss I wish u d same o. u've done a great job and a lot of people appreciate it. cheers. all d best this session boss, cheers 2 Likes 2 Shares |
(1) (2) (3) (4) (5) (6) (7) (8) (9) (10) (11) (of 15 pages)
(Go Up)
Sections: politics (1) business autos (1) jobs (1) career education (1) romance computers phones travel sports fashion health religion celebs tv-movies music-radio literature webmasters programming techmarket Links: (1) (2) (3) (4) (5) (6) (7) (8) (9) (10) Nairaland - Copyright © 2005 - 2024 Oluwaseun Osewa. All rights reserved. See How To Advertise. 266 |