Welcome, Guest: Register On Nairaland / LOGIN! / Trending / Recent / New
Stats: 3,151,566 members, 7,812,830 topics. Date: Monday, 29 April 2024 at 08:13 PM

Nnasino's Posts

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:
I'm very sorry if this is not permitted.. How can I write a java program to compute fractions and display the result exactly( as fraction too) without turning it to decimal or rounding off/up.. Do I need to import any java package??
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:

class Course{
//It is standard code practice to make your instance variables (variables belonging to an object) private
//You can create getter and setter methods that will be used to get and set the value of the variable
private int creditLoad; //the number of units of this course
private String courseTitle; // course title
private int level; // the level for this course e.g MTH 101 is a 100 level course so level = 100;
private char gradeLetter; //The grade obtained in the course
private int score; //score = gradeValue(5 for A, 4 for B etc) * creditLoad

//example getter and setter methods
public int getCreditLoad(){
return creditLoad;
}
public void setCreditLoad(int creditLoad){
//this is a pro of using setters, you can check some constraints and the integrity of the data
if(creditLoad < 0)
throw new Exception("Credit load can not be negative"wink;
if(creditLoad > 20)
throw new Exception("Credit load can not be more than 20"wink;
this.creditLoad = creditLoad;
}

//Constructors are usually public because they are called from other classes
public Course(){

//Initialize the variables with default values.
level = 0;
gradeLetter = 'F';
creditLoad = 0;
courseTitle = null;
}
public Course(String courseTitle, int creditLoad){
//Initialize the variables provided
this.courseTitle = courseTitle; //Note the use of the this keyword. this is used to differentiate the courseTitle owned by the object and the one gotten from the function arguments
this.creditLoad = creditLoad;
//Initialize the other variables with default values
this.gradeLetter = 'F';
this.level = 0;
}

int setGrade(char grade){
//to be implemented
}
}


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.

class Course{
//Only one copy of this variable will be created. it can be accessed using the classname. Course.MAXIMUM_CREDITlOAD
private static int MAXIMUM_CREDITLOAD = 20;
//It is standard code practice to make your instance variables (variables belonging to an object) private
//You can create getter and setter methods that will be used to get and set the value of the variable
private int creditLoad; //the number of units of this course
private String courseTitle; // course title
private int level; // the level for this course e.g MTH 101 is a 100 level course so level = 100;
private char gradeLetter; //The grade obtained in the course
private int score; //score = gradeValue(5 for A, 4 for B etc) * creditLoad

//example getter and setter methods
public int getCreditLoad(){
return creditLoad;
}
public void setCreditLoad(int creditLoad){
//this is a pro of using setters, you can check some constraints and the integrity of the data
if(creditLoad < 0)
throw new Exception("Credit load can not be negative"wink;
if(creditLoad > MAXIMUM_CREDITLOAD) //within the class, we don't need to put the class name
throw new Exception("Credit load can not be more than 20"wink;
this.creditLoad = creditLoad;
}

//Constructors are usually public because they are called from other classes
public Course(){

//Initialize the variables with default values.
level = 0;
gradeLetter = 'F';
creditLoad = 0;
courseTitle = null;
}
public Course(String courseTitle, int creditLoad){
//Initialize the variables provided
this.courseTitle = courseTitle; //Note the use of the this keyword. this is used to differentiate the courseTitle owned by the object and the one gotten from the function arguments
this.creditLoad = creditLoad;
//Initialize the other variables with default values
this.gradeLetter = 'F';
this.level = 0;
}

int setGrade(char grade){
//to be implemented
}
}


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:
creditLoad
is 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).


Course mth101Object; //create the reference
mth101Object = new Course(); //create the object and let the reference point to it



Using Objects
Objects are used with the '.' notation. That is if we have an object
mth101Object
. We can do the following:

mth101Object.creditLoad = 4; //four unit course
mth101Object.courseTitle = "MTH 101";

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){
//statements
//statements
}


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.

class Course{
int creditLoad; //the number of units of this course
String courseTitle; // course title
int level; // the level for this course e.g MTH 101 is a 100 level course so level = 100;
char gradeLetter; //The grade obtained in the course
int score; //score = gradeValue(5 for A, 4 for B etc) * creditLoad

public Course(){
//Initialize the variables with default values.
level = 0;
gradeLetter = 'F';
creditLoad = 0;
courseTitle = null;
}
public Course(String courseTitle, int creditLoad){
//Initialize the variables provided
this.courseTitle = courseTitle; //Note the use of the this keyword. this is used to differentiate the courseTitle owned by the object and the one gotten from the function arguments
this.creditLoad = creditLoad;
//Initialize the other variables with default values
this.gradeLetter = 'F';
this.level = 0;
}

int setGrade(char grade){
//to be implemented
}
}



We can therefore create Course objects as follows:


Course course1 = new Course();
course1.courseTitle = "MTH 101";

Course course2 = new Course("MTH 101", 4);

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:

class ClassName{
int var1;
other variable declarations

int getVar1(){
}
other method declarations
}


For instance, a course class can be declared as follows:

class Course{
int creditLoad; //the number of units of this course
String courseTitle; // course title
int level; // the level for this course e.g MTH 101 is a 100 level course so level = 100;
char gradeLetter; //The grade obtained in the course
int score; //score = gradeValue(5 for A, 4 for B etc) * creditLoad

int setGrade(char grade){
//to be implemented
}

}
Nairaland / General / Re: My Experience With Racists. by nnasino(m): 2:20pm On Nov 30, 2014
quantumphysics:
fresh off the boat
thanks
Nairaland / General / Re: My Experience With Racists. by nnasino(m): 2:01pm On Nov 30, 2014
SirShymex:


Dayuum!!

The grand master teacher told me never to laugh at the next black person, but this is hella funny. grin

Anyway, FOBs always jump the gun, and most of them don't know how to act.

Hopefully, ol'boy will acclamatise with time and stop disgracing black folks.

However, according to scientists (lol), the odour has 2/3 year life span - he'll have to live with that for now. grin
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:

try
catch
throw
throws
finally


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...catch
block as follows:

try{
code that can potentially throw an exception
}catch(ExceptionName exceptionVariableName){
Exception handling code: //this code is called if an exception of type ExceptionName is thrown
}catch([i]AnotherExceptionName[i] exceptionVariableName2){
Notice that you can catch more than one exception :w
}finally{
any code in the finally block is executed regardless of whether an exception occurs or not
}


Now, looking at our code we can see at this point, we need some exception handling:

for(int course = 0; course < numOfCourses; course++){
//get the title/code of the course
System.out.print("Please enter the title/code of the course: "wink;
title = scan.nextLine();
//get the credit load/unit of the course
System.out.printf("Please enter the credit load of %s: ", title);
creditLoad =Integer.parseInt(scan.nextLine());
//get the letter grade obtained
System.out.printf("Please enter the grade letter of %s: ", title);
gradeLetter = scan.nextLine().charAt(0)
//calculate Total number of units and total grade point of the semester
//Convert the grade letter to a point A - 5, B -4 etc
//Add the grade point of this course to the total grade point of this semester
TGP += creditLoad * gradeValue(gradeLetter);
//Add the credit load of this course to the total number of units of this semester
TNU += creditLoad;
}

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...catch
block 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:

static int getCreditLoad(Scanner scan, String courseTitle){ //The function takes the scanner object and the course title as it's parameters
int result = 0; //The result to be returned
while(true){ //Keep asking for the credit load
try{ //Put the code in a try block to catch any exception that is thrown
System.out.printf("Please enter the credit load of %s: ", courseTitle); //Formatted print: this will be explained later on
result = Integer.parseInt(scan.nextLine());
//If the program reaches here then that means there was no error
//Let us now make sure that the user doesn't give us a ridiculous value. Credit load shouldn't be more than 25 at most
if(result > 25){
//the value is too large
throw new NumberFormatException("Credit load is too large"wink; //this throws our own exception, which will be handled also
}else if (result < 0){
//credit load cannot be negative
throw new NumberFormatException("Credit Load cannot be negative"wink;
}
}catch(NumberFormatException exc){
System.out.println("Error: " + exc.getMessage()); //Exceptions usually have information about themselves, including the errormessage
//exc.printStackTrace(); //This method is useful for debugging, it gives you a trace of all where and how the exceptions were generated
continue; //continue to the beginning of the loop
}
//if we get here then the program is fine and the credit load was read successfully so we leave the loop
break;
}
return result;
}


If we now replace the previous line with our function we get a better more robust program:


for(int course = 0; course < numOfCourses; course++){
//get the title/code of the course
System.out.print("Please enter the title/code of the course: "wink;
title = scan.nextLine();
//get the credit load/unit of the course
System.out.printf("Please enter the credit load of %s: ", title);
creditLoad = readCreditLoad(scan);
//get the letter grade obtained
System.out.printf("Please enter the grade letter of %s: ", title);
gradeLetter = scan.nextLine().charAt(0)
//calculate Total number of units and total grade point of the semester
//Convert the grade letter to a point A - 5, B -4 etc
//Add the grade point of this course to the total grade point of this semester
TGP += creditLoad * gradeValue(gradeLetter);
//Add the credit load of this course to the total number of units of this semester
TNU += creditLoad;
}


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.


static int gradeValue(Scanner scan, String courseTitle) {
char letter = 'f';
while (true) {
System.out.printf("Please enter the grade letter of %s: ", courseTitle);
letter = scan.nextLine().charAt(0); //Select the first character only
switch (letter) {
case 'a':
case 'A':
return 5;
case 'b':
case 'B':
return 4;
case 'c':
case 'C':
return 3;
case 'd':
case 'D':
return 2;
case 'e':
case 'E':
return 1;
case 'f':
case 'F':
return 0;
default:
System.out.println("Error: Please enter a grade letter from A to F"wink;
}
}
}


This is the full code:

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package learn;

import java.util.Scanner;

/**
*
* @author chigozirim
*/
public class GPA {

static int gradeValue(Scanner scan, String courseTitle) {
char letter = 'f';
while (true) {
System.out.printf("Please enter the grade letter of %s: ", courseTitle);
letter = scan.nextLine().charAt(0); //Select the first character only
switch (letter) {
case 'a':
case 'A':
return 5;
case 'b':
case 'B':
return 4;
case 'c':
case 'C':
return 3;
case 'd':
case 'D':
return 2;
case 'e':
case 'E':
return 1;
case 'f':
case 'F':
return 0;
default:
System.out.println("Error: Please enter a grade letter from A to F"wink;
}
}
}

static int getCreditLoad(Scanner scan, String courseTitle) { //The function takes the scanner object and the course title as it's parameters
int result = 0; //The result to be returned
while (true) { //Keep asking for the credit load
try { //Put the code in a try block to catch any exception that is thrown
System.out.printf("Please enter the credit load of %s: ", courseTitle); //Formatted print: this will be explained later on
result = Integer.parseInt(scan.nextLine());
//If the program reaches here then that means there was no error
//Let us now make sure that the user doesn't give us a ridiculous value. Credit load shouldn't be more than 25 at most
if (result > 25) {
//the value is too large
throw new NumberFormatException("Credit load is too large"wink; //this throws our own exception, which will be handled also
} else if (result < 0) {
//credit load cannot be negative
throw new NumberFormatException("Credit Load cannot be negative"wink;
}
} catch (NumberFormatException exc) {
System.out.println("Error: " + exc.getMessage()); //Exceptions usually have information about themselves, including the errormessage
//exc.printStackTrace(); //This method is useful for debugging, it gives you a trace of all where and how the exceptions were generated
continue; //continue to the beginning of the loop
}
//if we get here then the program is fine and the credit load was read successfully so we leave the loop
break;
}
return result;
}


public static void main(String[] args) {
int TNU = 0; // Total number of units
int TGP = 0; //Total grade point
double TTGP = 0.0; //Total of the TNUs
double TTNU = 0.0; //Total of the TGPs
int numOfCourses = 0; //the number of courses for a semester
String title = null; //title of a course
int creditLoad = 0; //Credit load of a course
char gradeLetter = 'F'; //Grade letter of a course
double CGPA = 0.0; //Cumulative grade point average

int numOfYears = 0;
Scanner scan = new Scanner(System.in);
System.out.print("Welcome, enter the number of years: "wink;
numOfYears = Integer.parseInt(scan.nextLine());
System.out.println();
for (int years = 1; years <= numOfYears; years++) {
//There are usually two semesters each year
for (int semester = 1; semester <= 2; semester++) {
//get the number of courses offered for the semester
System.out.printf("Please enter the number of courses for Semester %d: ", semester);
numOfCourses = Integer.parseInt(scan.nextLine());
//For all courses
for (int course = 0; course < numOfCourses; course++) {
//get the title/code of the course
System.out.print("Please enter the title/code of the course: "wink;
title = scan.nextLine();
//get the credit load/unit of the course
creditLoad = getCreditLoad(scan, title);
//calculate Total number of units and total grade point of the semester
//Convert the grade letter to a point A - 5, B -4 etc
//Add the grade point of this course to the total grade point of this semester
TGP += creditLoad * gradeValue(scan, title);
//Add the credit load of this course to the total number of units of this semester
TNU += creditLoad;
}
}
TTNU += TNU;
TNU = 0;
TTGP += TGP;
TGP = 0;
}
CGPA = TTGP / TTNU;
System.out.printf("Your CGPA is: %.3f%n", CGPA);
}

}


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:

int TNU = 0; // Total number of units
int TGP = 0; //Total grade point
double TTGP = 0.0; //Total of the TNUs
double TTNU = 0.0; //Total of the TGPs
int numOfCourses =0; //the number of courses for a semester
String title = null; //title of a course
int creditLoad = 0; //Credit load of a course
char gradeLetter = 'F'; //Grade letter of a course
double CGPA = 0.0; //Cumulative grade point average

- 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.


//Declare variable for holding the number of years
int numOfYears = 0;
Scanner scan = new Scanner(System.in);
System.out.print("Welcome, enter the number of years: "wink;
numOfYears = Integer.parseInt(scan.nextLine());
System.out.println();



- for all the years


From the statement we can deduce that we will use a for loop for this.

for(int years = 1; years <= numOfYears; years++){


}


- for all the semesters
Note that this is within the years for loop

//There are usually two semesters each year
for(int semester = 1; semester <= 2; semester++){


}

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


//get the number of courses offered for the semester
numOfCourses = Integer.parseInt(scan.nextLine());
//For all courses
for(int course = 0; course < numOfCourses; course++){
//get the title/code of the course
System.out.print("Please enter the title/code of the course: "wink;
title = scan.nextLine();
//get the credit load/unit of the course
System.out.printf("Please enter the credit load of %s: ", title);
creditLoad =Integer.parseInt(scan.nextLine());
//get the letter grade obtained
System.out.printf("Please enter the grade letter of %s: ", title);
gradeLetter = scan.nextLine().charAt(0)
//calculate Total number of units and total grade point of the semester
//Convert the grade letter to a point A - 5, B -4 etc
//Add the grade point of this course to the total grade point of this semester
TGP += creditLoad * gradeValue(gradeLetter);
//Add the credit load of this course to the total number of units of this semester
TNU += creditLoad;
}

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
switch
statement.


static int gradeValue(char letter){
static int gradeValue(char letter) {
switch (letter) {
case 'a':
case 'A':
return 5;
case 'b':
case 'B':
return 4;
case 'c':
case 'C':
return 3;
case 'd':
case 'D':
return 2;
case 'e':
case 'E':
return 1;
default:
return 0;
}
}

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
years
for loop

TTNU += TNU;
TNU = 0;
TTGP += TGP;
TGP = 0;



- CGPA = Total TGP / Total TNU
- Display the CGPA to the user



CGPA = TTGP / TTNU;
System.out.printf("Your CGPA is: %.3f%n", CGPA);


Combining the code together we have:


/*This is a good place to write information about your program. Including the use, your name, the date and the version.
* A commandline application for calculating CGPA. No exception handling.
*/
package learn;

import java.util.Scanner;

/**
*
* @author nnasino
*/
public class GPA {

static int gradeValue(char letter) {
switch (letter) {
case 'a':
case 'A':
return 5;
case 'b':
case 'B':
return 4;
case 'c':
case 'C':
return 3;
case 'd':
case 'D':
return 2;
case 'e':
case 'E':
return 1;
default:
return 0;
}
}

public static void main(String[] args) {
int TNU = 0; // Total number of units
int TGP = 0; //Total grade point
double TTGP = 0.0; //Total of the TNUs
double TTNU = 0.0; //Total of the TGPs
int numOfCourses = 0; //the number of courses for a semester
String title = null; //title of a course
int creditLoad = 0; //Credit load of a course
char gradeLetter = 'F'; //Grade letter of a course
double CGPA = 0.0; //Cumulative grade point average

int numOfYears = 0;
Scanner scan = new Scanner(System.in);
System.out.print("Welcome, enter the number of years: " );
numOfYears = Integer.parseInt(scan.nextLine());
System.out.println();
for (int years = 1; years <= numOfYears; years++) {
//There are usually two semesters each year
for (int semester = 1; semester <= 2; semester++) {
//get the number of courses offered for the semester
System.out.printf("Please enter the number of courses for Semester %d: ", semester ) ;
numOfCourses = Integer.parseInt(scan.nextLine() ) ;
//For all courses
for (int course = 0; course < numOfCourses; course++) {
//get the title/code of the course
System.out.print("Please enter the title/code of the course: " ) ;
title = scan.nextLine();
//get the credit load/unit of the course
System.out.printf("Please enter the credit load of %s: ", title) ;
creditLoad = Integer.parseInt(scan.nextLine()) ;
//get the letter grade obtained
System.out.printf("Please enter the grade letter of %s: ", title ) ;
gradeLetter = scan.nextLine().charAt(0 ) ;
//calculate Total number of units and total grade point of the semester
//Convert the grade letter to a point A - 5, B -4 etc
//Add the grade point of this course to the total grade point of this semester
TGP += creditLoad * gradeValue(gradeLetter ) ;
//Add the credit load of this course to the total number of units of this semester
TNU += creditLoad;
}
}
TTNU += TNU;
TNU = 0;
TTGP += TGP;
TGP = 0;
}
CGPA = TTGP / TTNU;
System.out.printf("Your CGPA is: %.3f%n", CGPA ) ;
}
}


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. smiley
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:

type nameOfMethod(parameter list){
body of method;
return avalue; //if type is not void
}

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

int sum(int a, int b){
//This function sums two numbers
return a + b; //using the two parameters passed to it.
}

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
Scanner
class 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
Scanner
class'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:

Scanner scan = new Scanner(System.in);

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:



class Primes{
static boolean isPrime(int number){ //isPrime is declared as static, so we can use it within main (main is also static)
if(number == 2)
return true;
for(int i = 2; i < number; i++){
if(number % i == 0) //If the number can be divided by any other number apart from 1 and itself
return false; //Then it is not prime
}
return true; //If not it is prime
}
public static void main(String[] args){ //type psvm and press tab, netbeans will complete this for you
int number = 0; //Variable for holding the maximum number
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the maximum number" ); //type sout and press tab
number = scan.nextInt();
int count = 0; //The number of primes found
for(int i = 2; i <= number; i++){
if(isPrime(i))
count++;
}
System.out.println("The number of primes between 1 and " + number + " is " + count);
}
}
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)
statement;

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(;wink
, 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:

for(int i = 0, j =12; i < j; i++).....
for(int height = 100; height > 20; height--)
for(int i = 0, j=23; (i < 10) && (23 > 4); i++)....


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:

for(int i = 1, j =4; i < 5; i++, j--)



One more thing before we conclude:
[b]break, continue and labels[\b]
A
break
exits the loop it is contained in. A
continue
skips 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

while(true){
statements;
statements;
if(someThing)
break;
}

In the snippet above, the condition for the loop is
true
therefore 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
break
keyword. 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:

while(i < 5){
statement;
statement2;
if(someThing)
continue;
statement3;
statement4;
statement5;
}

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:

for(int i = 0; i < 5; i++)
for(int j = 0; j < 5; j++)
break;

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:

loop1: for(int i =0; i < 5; i++)
for(int j =0; j < 5; j++)
break loop1;



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.
while
loop
Now, as i said earlier on in this course, Loops are simply a mechanism for making the computer repeat a task.
2.
do while
loop
3.
for
loop
We also have the
switch
statement. I will treat all of these one after the other.

1.
while
loop: The while loop is of the form:

while(condition)
statement;

the while allows us repeat
statement
until 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

while(condition){
statement;
statement;
statement;
....
statement;
}


2.
Do while
loop does basically the same thing with the while loop. It is of the form

do
statement;
while(condition);

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 :

for(initialization; condition; iteration)
statement;
or
for(initialization; condition;iteration){
statements;
statements;
......
statements;
}

In a for loop, there is the loop control variable.
Finally we have the switch statement. It is of the form

switch(variable):
case constant1:
statement;
statement;
...
break;
case constant2:
statement;
statement;
...
break;
case constant3:
statement;
statement;
...
break;
case constantn:
statement;
statement;
...
break;
default:
statement;
}

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




int count = 1;
while(count <= 10){
System.out.println("The square of " + count + " is " + (count*count));
count++;
}

the above code snippet displays the square of the first ten integers. This can be converted into a for loop as follows:


for(int count = 1; count <= 10; count++){
System.out.println("The square of " + count + " is " + (count*count));
}

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:

The Op has done justice to the problem but the question is somehow. If what you mean is: a program to take ten integers from the user and sum them, then the solution goes thus:

import java.util.Scanner; //imports the Scanner class

public class SumIntegers{

public static void main(String args[]){
Scanner input = new Scanner(System.in); //creates an object of the Scanner class to take input from keyboard
int number; //the integer declaration
int sum = 0; //declares the sum integer and initialize it to zero

for(int i = 1; i <= 10; i++){ //repeat the enclosed instructions 10 times

System.out.println("Please enter an integer:"wink;
number = input.nextInt(); //takes the integer from the user
sum = sum + number; //performs the addition operation

}

System.out.print("The sum of the ten integers entered is: " + sum);


}

}
Thanks boss, for the answer
Programming / Re: Java Tutorial For Beginners by nnasino(m): 6:02pm On Nov 20, 2014
JAGZZ:
nnasino, Please help with this question: Write a program to sum ten integers using Java
I don't really understand your question. Do you mean to sum the first ten integers? If so then this will work:

class Sum{
public static void main( String[] args){
int sum = 0;
for(int I = 1; I <= 10; I++){
sum += I;
}
System.out.println("Sum of first ten numbers: " + sum);
}
}

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:


That's fine, Nnasino.

The charges levied on the vendor site, including the weight value in dollars and the exchange rate equivalent in naira has to be borne by the client.

Thanks and have a good day.
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:


Hi Nnasino,

[size=13pt]INVOICE[/size]
Product 1: $14.98
Product 2: $15.00

Total Products Cost: $29.98
Local Freight Fee (eBay): $7.79
Freight Fee: $13
Service Charge: $10

Sub-Total: $60.77
Discount: -$0.00

TOTAL: $60.77 (N10,700)

Thanks.
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,

if(3 < 6){
//do something
}else{
//end the program
}


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 :

(3 < 2)
(34 > 32)
(3 == 2)
(3 <= 3)
(4 >= 3)
(5 != 0)
((4 % 2) == 0)
(true)
(false)


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 
if a > 1:
divide a, b and c by a

d = sqrt(b2 - 4 * a * c)

if d < 0:
display "Imaginery roots"
exit
x1 = -b + d / 2.0
x2 = -b - d /2.0

display x1 and x2

With this algorithm we can then write our program


class Quadratic{
public static void main(String[] args){
double a;
double b;
double c;
double d = 0.0;
//Note that you could declare all of them on the same line like this: double a, b, c;
a = 2.0;
b = 5.0;
c = 24.0;
if(a > 1){
a = a / a;
b = b / a;
c = c /a;
//When you have this kind of situation, you can write b /= a, c /=a, a += c, b -= c etc
}
d = Math.pow(b, 2) - 4 * a * c;
if (d < 0){
//if d is negative then there will be imaginery numbers which we are not supporting currently
System.out.println("Imaginery roots"wink;
}else{
d = Math.sqrt(d);
double x1 = -b + d / 100;
double x2 = -b - d /100;
System.out.println("The roots are: " + x1 + " and " + x2);
}
}
}


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 was what I did for the simple interest. I need corrections o.

public class Simpleinterest {

public static void main (String[] args) {
double principal = 2000;
double rate = 5;
double time = 5;

double result = (principal * rate * time)/(100);

System.out.println(result);

forgive the spacing typing with my nokia phone.
Correction pls.
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:
well done op. I am definitely following. I was able to run the hello world program and the continuous addition program.
They were successful.

I would try my hands on the simple interest tonight or tomorrow and paste my result here.
Keep the good work on bro.
Thanks a bunch.
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:
If i may humbly request from the OP if i could also help along the teaching process; at least, give answers to questions, give suggestions on understanding some concepts better? I have been coding in java for a while now and i understand it quit well. Will really like to help the beginners too.
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:
I dont want to spoil this thread but why is java designed to first import, instantiate and declare the system.in before you use it? Thats why i fled from java. In C#, you just use Console.ReadLine(), and thats it.
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 wink. 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
result1
and 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 + 1
which gives us
2
. We then add
2 + 2
which gives us
 4
. We then add
4+4
which 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;
float floatNumber;
double doubleNumber;
char character;
boolean isTrue;


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:

class Problem1{
public static void main(String[] args){
int result = 1; //declare and initialize result with 1
result = result + result; // line 3
System.out.println(result);
result = result + result;
System.out.println(result);
result = result + result;
System.out.println(result);
}
}


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
String
variable 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(""wink;
you will get an error because you typed system instead of System. Secondly,
All
lines of code end with a semicolon ';'. ignore the lines that end with }. {} braces group
lines
of 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, void
etc. 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:



class HelloWorld{ //line 1
public static void main(String[] args){ //line 2
//Say hello to the world line 3
System.out.println("Hello World!"wink; //line 4
} //line 5
} //line 6


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"wink

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"wink

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 grin ). 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:


@toti... i saw ur reply, well, i.must say Futo students are really gud... my cousin finished there too... pls when will you start java?...
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:


wow... torti... am so glad... thnks bro... happy new semester!!!! your d boss....
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
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.