Welcome, Guest: Register On Nairaland / LOGIN! / Trending / Recent / New
Stats: 3,150,843 members, 7,810,247 topics. Date: Saturday, 27 April 2024 at 02:12 AM

Java Tutorial For Beginners - Programming - Nairaland

Nairaland Forum / Science/Technology / Programming / Java Tutorial For Beginners (23681 Views)

C++ Tutorial For Beginners... Part 1... / For Beginners: Learn How To Create A Simple Android Native App / Programming Challenge For Beginners N20000 (2) (3) (4)

(1) (2) (3) (4) (5) (Reply) (Go Down)

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

Re: Java Tutorial For Beginners by Nobody: 9:22am On Nov 13, 2014
nnasino:
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.

ride on boss... following...

1 Like 1 Share

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

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

Re: Java Tutorial For Beginners by Excel23: 6:59am On Nov 14, 2014
Bumper to bumper
Re: Java Tutorial For Beginners by Nobody: 7:34am On Nov 14, 2014
finally, a java thread for beginners... #following
Re: Java Tutorial For Beginners by Following(m): 7:44am On Nov 14, 2014
Preboy:
finally, a java thread for beginners... #following
u de call me? tongue

1 Like

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

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

Re: Java Tutorial For Beginners by Nobody: 9:23pm On Nov 14, 2014
nnasino:
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.
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.
Re: Java Tutorial For Beginners by mgb4reel(m): 10:51pm On Nov 15, 2014
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.
Re: Java Tutorial For Beginners by mgb4reel(m): 11:03pm On Nov 15, 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.
Trust me, i understand your plight quit fine but the c# u mention is very similar to java as it also use 'using' in place of 'import' as used in java. Most of the things u said made u flew from java are also in C# as they are the rudiments of object-oriented languages(You import predefined classes to use them, you instantiate classes to use them) By the time you understand the principles of Object - oriented programming, you will see the need for all this, and migrating from one(java) to another(c#) will be very easy as they follow the same principles. As for the System.in you mention, You used that to specify to the Scanner class(used for data input) constructor that you wanna take your input from the standard input(keyboard). If your input is gonna be from a file, you just specified the file name to the constructor. If you follow this thread accordingly, am sure the OP will explain them in details.

2 Likes

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.
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
Re: Java Tutorial For Beginners by sconp: 7:28pm On Nov 16, 2014
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.
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
Re: Java Tutorial For Beginners by sconp: 11:24pm On Nov 16, 2014
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.
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 }}.
Re: Java Tutorial For Beginners by Nobody: 10:19am On Nov 17, 2014
nice one OP...

1 Like

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

Re: Java Tutorial For Beginners by Nobody: 4:08pm On Nov 19, 2014
wow.............................. this is a wonderful work OP............

1 Like

Re: Java Tutorial For Beginners by JAGZZ: 5:06pm On Nov 20, 2014
nnasino, Please help with this question: Write a program to sum ten integers using Java
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
Re: Java Tutorial For Beginners by mgb4reel(m): 7:07pm On Nov 20, 2014
JAGZZ:
nnasino, Please help with this question: Write a program to sum ten integers using Java
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);


}

}
Re: Java Tutorial For Beginners by JAGZZ: 7:44pm On Nov 20, 2014
nnasino:

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

Its actually to sum any 10 arbitrary integers. Thanks.
Re: Java Tutorial For Beginners by JAGZZ: 7:50pm On Nov 20, 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);


}

}

Yeah its to sum up any ten integers from the user. Thanks, I appreciate.
Re: Java Tutorial For Beginners by mgb4reel(m): 10:40am On Nov 21, 2014
JAGZZ:


Yeah its to sum up any ten integers from the user. Thanks, I appreciate.
You are welcome bro. Am happy i could help.
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
Re: Java Tutorial For Beginners by mgb4reel(m): 4:39pm On Nov 21, 2014
nnasino:

Thanks boss, for the answer
Ha, oga, I be ur boi ooo...anyways, you are welcome.

1 Like

Re: Java Tutorial For Beginners by mgb4reel(m): 4:39pm On Nov 21, 2014
nnasino:

Thanks boss, for the answer
Ha, oga, I be ur boi ooo...

1 Like

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

Re: Java Tutorial For Beginners by Nobody: 7:56pm 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);


}

}
wow smooth, I learnt something new today

2 Likes

(1) (2) (3) (4) (5) (Reply)

Programmers: At What Age Did You Start Programming? / I Want To Learn Computer Programming, What Language Should I Learn First? / Community Project(strictly Java)

(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. 164
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.