Bubble Sort Practice

The Catch:
Create a program that will sort ten numbers in a descending order.

Solution:
import java.io.*;
class bubblepractice
{
public static void main (String args[]) throws IOException
{
BufferedReader buff = new BufferedReader (new InputStreamReader (System.in));

System.out.println("Enter 10 numbers: ");
int[] numbers = new int [10]; // This signals that ten numbers will be entered by the user

for (int index=0; index<10; index ++) { numbers[index] = Integer.parseInt(buff.readLine()); // Every number entered by the user will be stored in the index of the array numbers } for (int total = 0; total < 10; total++) { for (int two = total + 1; two < 10; two++) // Variable two is the second number next to variable total { if (numbers[two] > numbers[total])
{
int container = numbers[two]; // Initialize the value of two in container if two is bigger than total
numbers[two] = numbers[total]; // store the value of total in two
numbers[total] = container; // store the value of total in the container
}
}
}

System.out.println("To put them in order...");

for (int display = 0; display<10; display++) { System.out.println(numbers[display]); } } }

Bubble Sort

Bubble Sort is the simplest way in sorting algorithms. It maybe not be that efficient but as a beginner, it is a must to study it since it steps through a list, arranging it until it appears in the right order.

For example, arrange the numbers 5,3,1,4, and 2.

Let's do this step by step.

  1. Get the first two numbers (5 and 3). Is 5 greater than 3? Yes. Swap the numbers and it becomes 3,5,1,4,2
  2. 3 remains in the first spot after swapped by 5. Compare 5 and 1. Is five greater than 1? Yes. Swap both numbers and it becomes 3,1,5,4,2.
  3. Proceed to the next step by comparing 5 and 4. Is five greater than 4? Yes, then swap the two numbers and it becomes 3,1,4,5,2.
  4. Is five greater than 2? Yes, then swap. It becomes 3,1,4,2,5
As you've noticed, it is not in the right order yet. We need bubble sort to work on that.

The idea of bubble sort is: by the use of three variables and nested loops, you can work on this comparisons to store each value on each variable until the correct order displays.

Exercise: Using TWO classes

Create a program that will allow the user to input his desired number of records to store with the use of arrays.

example:

Enter Number of records: 1

Name Course Year
Ethel Grace Bobis                                   B.S Computer Science1


Let's start with our the first class. Let's name it Sample2.


class Sample2
{
String Arr1[];
String Arr2[];
String Arr3[];
int nItems;

Sample2(int size)
{
Arr1 = new String[size];
Arr2 = new String[size];
Arr3 = new String[size];
nItems=0;
}

void insert (String val)
{
Arr1[nItems] = val;
Arr2[nItems] = val;
Arr3[nItems] = val;
nItems++;
}

void display ()
{
System.out.println("\t **** \t");
System.out.println("The values are: ");
System.out.println("Name" + "\t\t" + "Course" + "\t\t" + "Year");

for (int x = 0; x <= nItems;x++) { System.out.println(Arr1[x] + "\t\t" + Arr2[x] + "\t\t" + Arr3[x]); } } }



And with the second class, let's name it MClass2


import java.io.*;
public class MClass2
{
public static void main (String args[]) throws IOException
{
BufferedReader m = new BufferedReader( new InputStreamReader(System.in));

System.out.println("Enter number of Records: ");
int rec = Integer.parseInt(m.readLine());

Sample2 y = new Sample2 (rec);

for (int x=1; x<= rec; x++) { { System.out.println("Enter Name"); String name = m.readLine(); y.insert(name); } { System.out.println("Enter Course: "); String course = m.readLine(); y.insert(course); } { System.out.println("Enter Year: "); String year = m.readLine(); y.insert(year); } } y.display(); } }


What's the output? The same above isn't it? ;)

Using two or more classes

Try to open your JCreator, or whatever third party java application you have. You can also use plain notepad if you want and play it through the use of your CMD.

Let's use Sample as the class name for this one...


class Sample
{
int sum;

Sample()
{
sum = 0;
}

void getSum(int num1, int num2)
{
sum = num1+num2;
}

void display()
{
System.out.println("The sum is:" + sum);
}
}


Try to create a new class with the filename of MClass (without deleting your first class which is the sample), and paste the code below:


import java.io.*;
public class MClass
{
public static void main (String args[]) throws IOException
{
BufferedReader m = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter First Number: ");
int a = Integer.parseInt(m.readLine());
System.out.println("Enter Second Number: ");
int b = Integer.parseInt(m.readLine());

Sample x = new Sample();
x.getSum(a,b);
x.display();
}
}


What's your output? Interesting, isn't it? :D

Object Oriented Programming

From the word object,it is understood that you can touch and feel something from it. But unlike in the real world, object is different in programming.

A couple of things to remember in Object Oriented Programming are the following:

  • State 
    • also known as attributes
    • similar to variables (part of your object)
  • Behaviour
    • What your Object can do
    • Methods (part of your object)
      • Non Returning
      • Returning
  • Class
    • the blueprint of your program
  • Constructor Method
    • should be the same of the class and file name
    • they are the ones who makes up the object
    • is used to initialize the behaviour
  • Instantation
    • used in creating a new object
  • Parameters
    • used to pass or receive values
    • enclosed with an open and close parenthesis ()
Try to familiarize these words... for a better future in programming ;)

Runtime Error

So there's two kinds of errors: Runtime and the Compile-time.

The Runtime Error can only be found when the program is successfully compiled and an error occurs. The Compile-time error, which I think is the most common, can be found when compiling.

So the program I posted yesterday has an error due to long codings. There were right answers in the final round where it displays Wrong, but the score is added.

Here's the final and error-free code. Try it for yourself.

import java.io.*;
public class QnA
{
public static void main (String args[]) throws IOException
{
DataInputStream old = new DataInputStream (System.in);

int startexit;

int[][] love = {{3,4,5},{6,7,8,9}};
int[][] heart= {{1,2},{6,7,8,9}};
int[][] ambot = {{1,2},{3,4,5},};

String name;

System.out.println("Enter your name:");
name = old.readLine();


System.out.println("\t \t =============================================== \t \t");
System.out.println("\t \t =============================================== \t \t");
System.out.println("\t \t +++++++++++++ Questions & Answers +++++++++++++ \t \t");
System.out.println("\t \t =============================================== \t \t");
System.out.println("\t \t =============================================== \t \t");

System.out.println("\n\n\n Greetings " + name + "!");

System.out.println ("\n First Round: \n Instruction: In order to proceed to the the second and final round, you have to get 3 correct answers. Each correct answer costs 1 point only. Press only the number of your choice. \n Note: Invalid Choices are considered Wrong.");

System.out.println("\nPress 1 to Start or press any number to exit");
startexit = Integer.parseInt(old.readLine());

if (startexit == 1)
{

System.out.println("\t \t =============================================== \t \t");
System.out.println("\t \t +++++++++++++ Questions & Answers +++++++++++++ \t \t");
System.out.println("\t \t +++++++++++++++++ First Round +++++++++++++++++ \t \t");
System.out.println("\t \t =============================================== \t \t");

int n=0;
int correct=0;

// System.out.println ("\nStage 2");
System.out.println ("\nQuestion # 1");
System.out.println ("\nWhat is the Oldest Street in the Philippines?");
System.out.println ("\n1. Orion St.,C.D.O. City");
System.out.println ("\n2. Sulu St.,Sta Cruz Manila");
System.out.println ("\n3. Colon St.,Cebu");
System.out.println ("\n4. Quezon ave.Manila\n");

n=Integer.parseInt (old.readLine());

switch (n)
{
case 1: System.out.println ("\nWrong");
break;
case 2: System.out.println ("\nWrong");
break;
case 3: System.out.println ("\nCorrect");
correct = correct +1;
break;
case 4: System.out.println ("\nWrong");
break;
default : System.out.println ("\nInvalid Choice");
}


System.out.println ("\nQuestion # 2");
System.out.println ("\nWhat is the most consumed fruit in the world?");
System.out.println ("\n1. Grapes");
System.out.println ("\n2. Bananas");
System.out.println ("\n3. Apple");
System.out.println ("\n4. Mangoes\n");

n=Integer.parseInt (old.readLine());

switch (n)
{
case 1: System.out.println ("\nWrong");
break;
case 2: System.out.println ("\nCorrect");
correct = correct +1;
break;
case 3: System.out.println ("\nWrong");
break;
case 4: System.out.println ("\nWrong");
break;
default : System.out.println ("\nInvalid Choice");
}

System.out.println ("\nQuestion # 3");
System.out.println ("\nWhat is Biggest animal in the world?");
System.out.println ("\n1. blue whales");
System.out.println ("\n2. elephants");
System.out.println ("\n3. Polar Bears");
System.out.println ("\n4. flies and mosquitoes");

n=Integer.parseInt (old.readLine());

switch (n)
{
case 1: System.out.println ("\nCorrect");
correct = correct +1;
break;
case 2: System.out.println ("\nWrong");
break;
case 3: System.out.println ("\nWrong");
break;
case 4: System.out.println ("\nWrong");
break;
default : System.out.println ("\nInvalid Choice");
}

System.out.println ("\nQuestion # 4");
System.out.println ("\nWho is the Greek Goddess of Wisdom?");
System.out.println ("\n1. Apollo");
System.out.println ("\n2. Demeter");
System.out.println ("\n3. Athena");
System.out.println ("\n4. Zeus\n");

n=Integer.parseInt (old.readLine());

switch (n)
{
case 1: System.out.println ("\nWrong");
break;
case 2: System.out.println ("\nWrong");
break;
case 3: System.out.println ("\nCorrect");
correct = correct +1;
break;
case 4: System.out.println ("\nWrong");
break;
default : System.out.println ("\nInvalid Choice");
}

System.out.println ("\nQuestion # 5");
System.out.println ("\nWhat is the largest city in the world?");
System.out.println ("\n1. Tokyo-Yokohama, Japan");
System.out.println ("\n2. Manila, Philippines");
System.out.println ("\n3. New York, United States");
System.out.println ("\n4. Sao Paulo, Brazil\n");

n=Integer.parseInt (old.readLine());

switch (n)
{
case 1: System.out.println ("\nCorrect");
correct = correct +1;
break;
case 2: System.out.println ("\nWrong");
break;
case 3: System.out.println ("\nWrong");
break;
case 4: System.out.println ("\nWrong");
break;
default : System.out.println ("\nInvalid Choice");
}

for (int ctr = 50; ctr>0; ctr--)
{
System.out.println("Loading");
}

System.out.println ("\n\nCorrect answers:" + correct);

if (correct < 3) { System.out.println("Sorry, you failed. You cannot proceed to the final level"); System.out.println("\n\nGoodbye!" + " " + heart[0][0] + love[0][1] + ambot[1][0] + "! :)"); } else { System.out.println("\n\nCongratulations! You passed and you can now proceed to the next level"); int decision; System.out.println("\nDo you wish to continue? Press 1 if yes or press any number if no."); decision = Integer.parseInt(old.readLine()); if (decision == 1) { System.out.println("\t \t =============================================== \t \t"); System.out.println("\t \t +++++++++++++ Questions & Answers +++++++++++++ \t \t"); System.out.println("\t \t +++++++++++++++++ Final Round +++++++++++++++++ \t \t"); System.out.println("\t \t =============================================== \t \t"); System.out.println ("\n Final Round: \n Instruction: In order to win the game, you have to get at least 9 points. Each correct answer costs 2 points only. Type the number of your answer only \n Note: Points in the first round will be added. Invalid Choices are considered Wrong."); int answers; System.out.println("\n\nWhat festival is celebrated in Cebu every third Sunday of January? "); System.out.println("\n1.Sinulog \n2.Durian\n3.Albay\n4.Nile River\n5.San Lorenzo Ruiz"); answers = Integer.parseInt(old.readLine()); switch (answers) { case 1 : System.out.println("Correct!"); correct = correct + 2; break; case 2 : System.out.println("Wrong!"); break; case 3 : System.out.println("Wrong!"); break; case 4 : System.out.println("Wrong!"); break; case 5 : System.out.println("Wrong!"); break; default: System.out.println("Wrong!"); break; } System.out.println("\nWho was the first Filipino Saint? "); System.out.println("\n1.Sinulog \n2.Durian\n3.Albay\n4.Nile River\n5.San Lorenzo Ruiz"); answers = Integer.parseInt(old.readLine()); switch (answers) { case 1 : System.out.println("Wrong!"); break; case 2 : System.out.println("Wrong!"); break; case 3 : System.out.println("Wrong!"); break; case 4 : System.out.println("Wrong!"); break; case 5 : System.out.println("Correct!"); correct = correct + 2; break; default: System.out.println("Wrong!"); break; } System.out.println("\nWhat is the longest river in the world? "); System.out.println("\n1.Sinulog \n2.Durian\n3.Albay\n4.Nile River\n5.San Lorenzo Ruiz"); answers = Integer.parseInt(old.readLine()); switch (answers) { case 1 : System.out.println("Wrong!"); break; case 2 : System.out.println("Wrong!"); break; case 3 : System.out.println("Wrong!"); break; case 4 : System.out.println("Correct!"); correct = correct + 2; break; case 5 : System.out.println("Wrong!"); break; default: System.out.println("Wrong!"); break; } System.out.println("\nWhere can you find Mayon Volcano?"); System.out.println("\n1.Sinulog \n2.Durian\n3.Albay\n4.Nile River\n5.San Lorenzo Ruiz"); answers = Integer.parseInt(old.readLine()); switch (answers) { case 1 : System.out.println("Wrong!"); break; case 2 : System.out.println("Wrong!"); break; case 3 : System.out.println("Correct!"); correct = correct + 2; break; case 4 : System.out.println("Wrong!"); break; case 5 : System.out.println("Wrong!"); break; default: System.out.println("Wrong!"); break; } for (int ctr = 50; ctr>0; ctr--)
{
System.out.println("Loading");
}

System.out.println("\n\n\n");

if (correct >=9)
{
System.out.println("Congratulations! You won!");
System.out.println ("\nOverall Score:" + correct);


System.out.println("\t \t ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \t \t");
System.out.println("\t \t ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \t \t");
System.out.println("\t \t ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \t \t");
System.out.println("\t \t ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \t \t");
System.out.println("\t \t ~~~~~~~~~~~~~~~~ Congratulations! ~~~~~~~~~~~~~~ \t \t");
System.out.println("\t \t ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \t \t");
System.out.println("\t \t ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \t \t");
System.out.println("\t \t ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \t \t");
System.out.println("\t \t ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \t \t");
}
else
{
System.out.println("Sorry you failed. Better luck next time");
System.out.println ("\nOverall Score:" + correct);
}
}

else
System.out.println("\n\nGoodbye!" + " " + heart[0][0] + love[0][1] + ambot[1][0] + "! :)");

}


}
else

System.out.println("\n\nGoodbye!" + " " + heart[0][0] + love[0][1] + ambot[1][0] + "! :)");
}
}



Programmers:

All in One: SOLVED!

So, now we finished the program we are making - A game. So here's the code, check it out:

import java.io.*;
public class QnA
{
public static void main (String args[]) throws IOException
{
DataInputStream old = new DataInputStream (System.in);

int startexit;

int[][] love = {{3,4,5},{6,7,8,9}};
int[][] heart= {{1,2},{6,7,8,9}};
int[][] ambot = {{1,2},{3,4,5},};

String name;

System.out.println("Enter your name:");
name = old.readLine();


System.out.println("\t \t =============================================== \t \t");
System.out.println("\t \t =============================================== \t \t");
System.out.println("\t \t +++++++++++++ Questions & Answers +++++++++++++ \t \t");
System.out.println("\t \t =============================================== \t \t");
System.out.println("\t \t =============================================== \t \t");

System.out.println("\n\n\n Greetings " + name + "!");

System.out.println ("\n First Round: \n Instruction: In order to proceed to the the second and final round, you have to get 3 correct answers. Each correct answer costs 1 point only. Press only the number of your choice. \n Note: Invalid Choices are considered Wrong.");

System.out.println("\nPress 1 to Start or press any number to exit");
startexit = Integer.parseInt(old.readLine());

if (startexit == 1)
{

System.out.println("\t \t =============================================== \t \t");
System.out.println("\t \t +++++++++++++ Questions & Answers +++++++++++++ \t \t");
System.out.println("\t \t +++++++++++++++++ First Round +++++++++++++++++ \t \t");
System.out.println("\t \t =============================================== \t \t");

int n=0;
int correct=0;

// System.out.println ("\nStage 2");
System.out.println ("\nQuestion # 1");
System.out.println ("\nWhat is the Oldest Street in the Philippines?");
System.out.println ("\n1. Orion St.,C.D.O. City");
System.out.println ("\n2. Sulu St.,Sta Cruz Manila");
System.out.println ("\n3. Colon St.,Cebu");
System.out.println ("\n4. Quezon ave.Manila\n");

n=Integer.parseInt (old.readLine());

switch (n)
{
case 1: System.out.println ("\nWrong");
break;
case 2: System.out.println ("\nWrong");
break;
case 3: System.out.println ("\nCorrect");
correct = correct +1;
break;
case 4: System.out.println ("\nWrong");
break;
default : System.out.println ("\nInvalid Choice");
}


System.out.println ("\nQuestion # 2");
System.out.println ("\nWhat is the most consumed fruit in the world?");
System.out.println ("\n1. Grapes");
System.out.println ("\n2. Bananas");
System.out.println ("\n3. Apple");
System.out.println ("\n4. Mangoes\n");

n=Integer.parseInt (old.readLine());

switch (n)
{
case 1: System.out.println ("\nWrong");
break;
case 2: System.out.println ("\nCorrect");
correct = correct +1;
break;
case 3: System.out.println ("\nWrong");
break;
case 4: System.out.println ("\nWrong");
break;
default : System.out.println ("\nInvalid Choice");
}

System.out.println ("\nQuestion # 3");
System.out.println ("\nWhat is Biggest animal in the world?");
System.out.println ("\n1. blue whales");
System.out.println ("\n2. elephants");
System.out.println ("\n3. Polar Bears");
System.out.println ("\n4. flies and mosquitoes");

n=Integer.parseInt (old.readLine());

switch (n)
{
case 1: System.out.println ("\nCorrect");
correct = correct +1;
break;
case 2: System.out.println ("\nWrong");
break;
case 3: System.out.println ("\nWrong");
break;
case 4: System.out.println ("\nWrong");
break;
default : System.out.println ("\nInvalid Choice");
}

System.out.println ("\nQuestion # 4");
System.out.println ("\nWho is the Greek Goddess of Wisdom?");
System.out.println ("\n1. Apollo");
System.out.println ("\n2. Demeter");
System.out.println ("\n3. Athena");
System.out.println ("\n4. Zeus\n");

n=Integer.parseInt (old.readLine());

switch (n)
{
case 1: System.out.println ("\nWrong");
break;
case 2: System.out.println ("\nWrong");
break;
case 3: System.out.println ("\nCorrect");
correct = correct +1;
break;
case 4: System.out.println ("\nWrong");
break;
default : System.out.println ("\nInvalid Choice");
}

System.out.println ("\nQuestion # 5");
System.out.println ("\nWhat is the largest city in the world?");
System.out.println ("\n1. Tokyo-Yokohama, Japan");
System.out.println ("\n2. Manila, Philippines");
System.out.println ("\n3. New York, United States");
System.out.println ("\n4. Sao Paulo, Brazil\n");

n=Integer.parseInt (old.readLine());

switch (n)
{
case 1: System.out.println ("\nCorrect");
correct = correct +1;
break;
case 2: System.out.println ("\nWrong");
break;
case 3: System.out.println ("\nWrong");
break;
case 4: System.out.println ("\nWrong");
break;
default : System.out.println ("\nInvalid Choice");
}

for (int ctr = 50; ctr>0; ctr--)
{
System.out.println("Loading");
}

System.out.println ("\n\nCorrect answers:" + correct);

if (correct < 3) { System.out.println("Sorry, you failed. You cannot proceed to the final level"); System.out.println("\n\nGoodbye!" + " " + heart[0][0] + love[0][1] + ambot[1][0] + "! :)"); } else { System.out.println("\n\nCongratulations! You passed and you can now proceed to the next level"); int decision; System.out.println("\nDo you wish to continue? Press 1 if yes or press any number if no."); decision = Integer.parseInt(old.readLine()); if (decision == 1) { System.out.println("\t \t =============================================== \t \t"); System.out.println("\t \t +++++++++++++ Questions & Answers +++++++++++++ \t \t"); System.out.println("\t \t +++++++++++++++++ Final Round +++++++++++++++++ \t \t"); System.out.println("\t \t =============================================== \t \t"); System.out.println ("\n Final Round: \n Instruction: In order to win the game, you have to get at least 9 points. Each correct answer costs 2 points only. Type the number of your answer only \n Note: Points in the first round will be added. Invalid Choices are considered Wrong."); int answers; System.out.println("\n\nWhat festival is celebrated in Cebu every third Sunday of January? "); System.out.println("\n1.Sinulog \n2.Durian\n3.Albay\n4.Nile River\n5.San Lorenzo Ruiz"); answers = Integer.parseInt(old.readLine()); switch (answers) { case 1 : System.out.println("Correct!"); correct = correct + 2; break; case 2 : System.out.println("Wrong!"); break; case 3 : System.out.println("Wrong!"); break; case 4 : System.out.println("Wrong!"); break; case 5 : System.out.println("Wrong!"); break; default: System.out.println("Wrong!"); break; } System.out.println("\nWho was the first Filipino Saint? "); System.out.println("\n1.Sinulog \n2.Durian\n3.Albay\n4.Nile River\n5.San Lorenzo Ruiz"); answers = Integer.parseInt(old.readLine()); switch (answers) { case 1 : System.out.println("Wrong!"); break; case 2 : System.out.println("Wrong!"); break; case 3 : System.out.println("Wrong!"); break; case 4 : System.out.println("Wrong!"); break; case 5 : System.out.println("Correct!"); correct = correct + 2; break; default: System.out.println("Wrong!"); break; } System.out.println("\nWhat is the longest river in the world? "); System.out.println("\n1.Sinulog \n2.Durian\n3.Albay\n4.Nile River\n5.San Lorenzo Ruiz"); answers = Integer.parseInt(old.readLine()); switch (answers) { case 1 : System.out.println("Wrong!"); break; case 2 : System.out.println("Wrong!"); break; case 3 : System.out.println("Wrong!"); break; case 4 : System.out.println("Wrong!"); correct = correct + 2; break; case 5 : System.out.println("Wrong!"); break; default: System.out.println("Wrong!"); break; } System.out.println("\nWhere can you find Mayon Volcano?"); System.out.println("\n1.Sinulog \n2.Durian\n3.Albay\n4.Nile River\n5.San Lorenzo Ruiz"); answers = Integer.parseInt(old.readLine()); switch (answers) { case 1 : System.out.println("Wrong!"); break; case 2 : System.out.println("Wrong!"); break; case 3 : System.out.println("Wrong!"); correct = correct + 2; break; case 4 : System.out.println("Wrong!"); break; case 5 : System.out.println("Wrong!"); break; default: System.out.println("Wrong!"); break; } for (int ctr = 50; ctr>0; ctr--)
{
System.out.println("Loading");
}

System.out.println("\n\n\n");

if (correct >=9)
{
System.out.println("Congratulations! You won!");
System.out.println ("\nOverall Score:" + correct);


System.out.println("\t \t ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \t \t");
System.out.println("\t \t ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \t \t");
System.out.println("\t \t ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \t \t");
System.out.println("\t \t ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \t \t");
System.out.println("\t \t ~~~~~~~~~~~~~~~~ Congratulations! ~~~~~~~~~~~~~~ \t \t");
System.out.println("\t \t ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \t \t");
System.out.println("\t \t ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \t \t");
System.out.println("\t \t ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \t \t");
System.out.println("\t \t ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \t \t");
}
else
{
System.out.println("Sorry you failed. Better luck next time");
System.out.println ("\nOverall Score:" + correct);
}
}

else
System.out.println("\n\nGoodbye!" + " " + heart[0][0] + love[0][1] + ambot[1][0] + "! :)");

}


}
else

System.out.println("\n\nGoodbye!" + " " + heart[0][0] + love[0][1] + ambot[1][0] + "! :)");
}
}


Programmers:

All in One

I'm in the middle of creating a program [Java] with the help of two other pals I got in school. We will actually defend that program within this week. We are required to use four out of the five statements, namely:

  • If statement (which includes the Dangling If's and others)
  • Arrays (Whether the normal array or the 2D)
  • Switch (commonly known as Case)
  • Loop (any of the loops)
So array is divided into two which means we have the power to choose which array to use, and that makes it four.

I'll post the code as soon as we are able to merge our codes. Further discussions would be available regarding the program.

Problem 2: Arrays

Based from the previous problem about arrays, here's another thing which is similar to that problem: Create a program that will allow the user to enter ten numbers and sort the numbers in an ascending and descending order. Then, display the highest and the lowest value of the ten numbers given by the user.

import java.io.*;
import java.util.Arrays;

public class Oc13
{
public static void main (String args[]) throws IOException
{

DataInputStream whatever = new DataInputStream (System.in);

int earth[] = new int [10];
int temp;

System.out.println("Enter 10 numbers: ");

for (int i = 0; i< earth.length/2; ++i ) { temp = earth[i]; earth[i] = earth[earth.length - i - 1]; earth[earth.length - i - 1] = temp; } System.out.println("Descending Order: " + Arrays.toString(earth)); System.out.println("Highest is " + earth[0]); // System.out.println("Lowest is " + earth[10]); } }

Problem: Loop

create a program based on the sample output below:

Enter Number: 5
*
**
***
****
*****


import java.io.*;
class s31
{
public static void main (String args[]) throws IOException
{
DataInputStream ethel=new DataInputStream (System.in);

int ctr;

System.out.println("Enter number ");
ctr=Integer.parseInt(ethel.readLine());


for(int i = 1; i <=ctr; i++)

{ for(int j = 1; j <=i; j++)
{ System.out.print("*"); }
System.out.println(); } } }

Loops

There are three different kinds of loops: while, for, and do-while loops.

The uses of these loops are almost alike. But, there are some cases that they're different. It only depends on how you use it.

FOR LOOP

  • repeats for a specified number of times
Syntax:
for(initialization; comparison ;increment or decrement)
{statements;}

WHILE LOOP
  • a loop that repeats until a certain condition is satisfied
Syntax:
while(condition)
{statements;)


DO-WHILE LOOP
  • unlike the while loop, the do-while loop tests the condition at the end of the loop
Syntax:
do
{statements;}
while(condition);

Problem: Array

Create a program that will allow the user to enter ten numbers and sort the numbers in an ascending and descending order.


import java.io.*;
import java.util.Arrays;

public class Oc13
{
public static void main (String args[]) throws IOException
{

DataInputStream whatever = new DataInputStream (System.in);

int earth[] = new int [10];
int temp;

System.out.println("Enter 10 numbers: ");

for (int i = 0; i< earth.length/2; ++i )

{ temp = earth[i];
earth[i] = earth[earth.length - i - 1];
earth[earth.length - i - 1] = temp; }
System.out.println("Descending Order: " + Arrays.toString(earth));
} }

Arrays


int[] number;
int number

String[] words;
String words;


Try to differentiate the codes above.

The codes on the left side are different from the right. The codes on the left are arrays. What is an array?

An array is similar to any other variables, only that it has its own subarrays and elements. Subarrays are arrays within an array, while elements are found inside the array.


example:

int[] variable = {element, element, element, . . . . .}
or
String[] variable = {{element},{element},{element}}


In declaring an array, the syntax is int[] variable = new Int[size of your array]

Problem 2: CharAt and length

Similar the previous problem, create a program that will allow the user to enter a string (word or phrase) that will also show the second character and the length based on the string entered by the user.

import java.io.*;
class s30
{
public static void main (String args[]) throws IOException
{
DataInputStream k=new DataInputStream (System.in);

String a;

System.out.println("Enter String: ");
a=k.readLine();
char s = a.charAt(1);
System.out.println(s);
System.out.println(a.length());
}
}

Problem: CharAt and String

Create a program that will display the first letter of a string as well as display the string's length. Note that the string will not be provided by the user.

class s30
{
public static void main (String args[])
{
String a = "Hello World";
char s = a.charAt(0);
System.out.println(s);
System.out.println(a.length());
}
}

CharAt and Length

CharAt

  • returns the character at the specified index in a string
  • written as CharAt() with the index inside the ()
  • the index starts with a zero (example: with the word Hi, H is 0 and i is 1)
  • includes special characters and spaces
example:
HelloWorld.CharAt(0) is the letter H
HelloWorld.CharAt(1) is the letter e
HelloWorld.CharAt(2) is the letter l
HelloWorld.CharAt(3) is the letter l
HelloWorld.CharAt(4) is the letter o
HelloWorld.CharAt(5) is the letter W


Length
  • shows the length of a string
  • starts at zero
  • includes special characters and spaces
  • written as string.length

IF statement

You have noticed that in the previous post, the first Problem given (and solved) uses the If-else statement.

The If-Else statement can be used for a series of tests on a value. The else part contains only another if statement  If you use if for the else part, it won't easy to see which of the series of tests are identical. Therefore, it is better to write them as If else.


In some cases, programmers use the Dangling If where there are a series of IF's, while some use the else if formatting since it the codes are clearer and readable.

Problem 1: Input and Output

Create a program that will let the user enter four numbers. If the first number is greater than the second number, and the third number is less than the fourth number, or, if the first number is greater than the second number, and the third number is less than one, display TRUE. Else, display FALSE.


import java.io.*;
public class New{
public static void main (String args[]) throws IOException
{
DataInputStream n=new DataInputStream (System.in);
int a=0;
int b=0;
int c=0;
int d=0;
System.out.println("Enter First Number: ");
a=Integer.parseInt (n.readLine());
System.out.println("Enter Second Number: ");
b=Integer.parseInt (n.readLine());
System.out.println("Enter Third Number: ");
c=Integer.parseInt (n.readLine());
System.out.println("Enter Fourth Number: ");
d=Integer.parseInt (n.readLine());
if (a>b && c<d || a >b && c<1)

System.out.println("TRUE");
else System.out.println("FALSE"); } }

Input and Output

if you want to input something in Java, you should add import java.io.*; before your class name, throws IOException after (String args[]), and DataInputStream for buffering


Try this:
import java.io.*;
public class import
{
   public static void main (String args[]) throws IOException
    {
      DataInputStream newinput = new DataInputStream(System.in);
      String new;
      System.out.println("Enter phrase here:");
      new = newinput.readLine();
      System.out.println(new);
     }
}


Note that newinput can be replaced by any word or letter which depends to the programmer. Let's say that the programmer wants to put his name on it, let's say his name is Nick, Nick can put it this way...

      DataInputStream Nick = new DataInputStream(System.in);
      String new;
      System.out.println("Enter phrase here:");
      new = Nick.readLine();
      System.out.println(new);
     }
}


Make sure also, that the uses of newinput in the program are replaced by Nick.


Notice: readLine should always be written as readLine() with an uppercased L.

Displaying "Hello World"

Open your JCreators (or whatever you are using), and create a new file or project.


Note that whatever the name of your project is, that should be the same name of your class (to be discussed in a short while). Also take note that Java is case sensitive which means Int and int are different.

After setting up your project, you will now see your workspace (where you'll type in the codes).
Our aim today is to display the string Hello World to your screens upon executing your program. So here's the code you have to type in:


public class
{
public static void main (String args[])
{
System.out.println("Hello World");
}
}


So as you have noticed, every statement in Java should end with an ;

Also, take note that public should always be lowercased while String and System should be written with a capital S.

System.out.println can also be written as System.out.print. Try it yourself!

Primitive Data Types

Before we'll proceed to programming, I'll start off by introducing you the eight different primitive data types in Java.

BYTE

  •  useful for saving a memory in huge arrays. Sometimes, it can be replaced by an Int (or Integer)

SHORT

  • from the word itself, it means short, or small amount of numbers

LONG

  • an opposite of short, it stores large amount of numbers (ex. 1234566789003252)

DOUBLE

  • this data type goes for decimal number (just like float)
INT
  • the most common data type where double, long, short, and byte can be stored in substitute with some differences to their types (like int can't hold decimal numbers)
BOOLEAN
  • answers only true or false, or simply, yes or no
CHAR
  • single letters are called characters
  • example: 'A ' is a character "AB" is a string

Note: Notice that characters are placed with an open and close single quotation marks while strings are placed with an open and close double quotation marks.

Hello World

Hello there!

Programming may need patience and logic, but to those who are willing to learn but can't afford that much, I'm here to show you how to work things out.

First, we'll  study Sun's most popular language, Java, but we'll start with the basics. Of course, you're gonna need a Java application installer as well as a JDK.

There are different softwares available for Java programming. Netbeans and JCreator, are some examples. But, I recommend you guys to use JCreator (Since i'm using it).

So, are you ready to start? I'll provide you a link where you can download JCreator. Click Here to download it.

Extended Search

Custom Search