Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Simple 'Try and Catch' Example


import java.io.*;

public class TryCatchExample
{
public static void main (String args[]) throws IOException
{
BufferedReader HelloWorld = new BufferedReader(new InputStreamReader(System.in));


System.out.println("Enter A Number: ");


try
{
int GalaxyNumber = Integer.parseInt(HelloWorld.readLine());
}


catch (NumberFormatException ShowError)
{
System.out.println("Enter A Number: ");
}
}

you can also have...


catch (NumberFormatException ShowError)
{
System.out.println(ShowError);
}



instead of...


catch (NumberFormatException ShowError)
{
System.out.println("Enter A Number: ");
}


... to know the error.

Try and Catch

Try - Make an attempt or effort to do something
Catch - Intercept and Hold

Syntax:

try
{
statement(s);
}

catch (Exception Handler Tag)
{
statement(s);
}


The try and catch  allows you to test a block of errors. Once it encounters a block of errors in the try, it passes it to the tag. A tag is a variable that hold the exception. The statements under the catch are to be executed once the try receives an error (it catches the errors from the try).

Exception Handler is an exception. An exception an error. Famous exceptions are IOException and NumberFormatException.

For an example of a try and catch, refer to the next post.

Creating a GUI of a Simple Calculator



The image above is a simple calculator found in Windows; while the image below is a simplier version of calculator compared to the one above.


And yes, it is created in Java. Try to create your own version of a Java Calculator using the simple operations. The code will be posted in a few days.

PS
Just the GUI. Never mind the functions yet.

Ways to Use Inheritance

There are two ways to use Inheritance in Java.

1. Using the Extend keyword
     As you have learned from the previous lesson, the extend keyword is used in Method Overriding, which is a part of Polymorphism. We use it to refer the different methods and variables in a parent or super class that can be used in the parent of child class. Given the example from the previous post...


class first
{
int number;

void Add()
{
number=number+1;
}

void Subtract()
{
number=number-1;
}
}
class second extends first
{
void Add()
{
number=number*1;
}
void Divide()
{
number=number/1;
}
}
public class MClass
{
public static void main (String args[])
{
first one = new first();
one.Add();
one.Subtract();

second two = new second();
two.Add();
two.Divide()
}
}



2. Constructor Method
     A constructor method is commonly used (beginners) in creating methods in a simple program. The constructor method uses parameters to connect values from the object class to the main class. For example, given a Sample Class and a Main Class...


class Sample
{
void test()
{
System.out.println("Test");
}
}

public class MainClass
{
public static void main (String args[])
{
Sample x = new Sample();
}
}


The output will only display Test.

Inheritance

In Java, the following terms are often used:

  • Super Class - the topmost part of the class
  • Parent Class - the class before the child class
  • Child Class - the last class in the program
To understand fully, here's a sample of a family tree.







Obviously, the child (classes) are the following:

  • Me
  • Brother
  • Sister
  • Cousin; and
  • OTHER Cousin
The Parent Classes are:
  • Mommy and Daddy Smith
  • Uncle and Aunt Trotter
  • Aunt and OTHER A.N
The Super Class are:
  • Grandad and Granny Jones
  • Great Grandad and Great Granny Bloggs
However, Java does not support multiple inheritance. Java can only hold one Super Class, one Parent Class, and one Child Class.

GUI Basics

A GUI is an acronym of Graphical User Interface, and is sometimes pronounced as Gooey. Visual Basic has a very good example of GUI wherein you can draw your objects freely with the use of the mouse. However, in Java, you have to plot it point by point.

The first thing in creating a GUI in Java is to use everything in the swing package and to override swing's JFrame by using the extend keyword.

Our main goal in this lesson is to create a simple GUI of an ATM Machine with two labels and textboxes (Card Number and Pin), two buttons (OK and Cancel) and name it ATM.





Below is the code with explanations...


import javax.swing.*;  //use everything within the swing package
public class CodeGalaxy extends JFrame  //overrides JFrame
{

JTextField txt1 = new JTextField();  //JTextField is equivalent to a textbox
JLabel CardN = new JLabel("Card Number: ");  //JLabel is equivalent to a label

JTextField txt2 = new JTextField();
JLabel PIN = new JLabel("Pin: ");

JButton OKbtn = new JButton("OK");  //JButton is equivalent to a command button
JButton Can = new JButton("Cancel");


public CodeGalaxy()   //constructor method with the same name of your class
{

//shows the output of the Card Number


getContentPane().setLayout(null);   //set to nothing / null 
CardN.setBounds(70,10,90,10); //setBounds defines the boundary of your object
getContentPane().add(CardN);

txt1.setBounds(150,10,150,18);
getContentPane().add(txt1);

//same flow of idea as to the Card Number//

//shows the output of the PIN
PIN.setBounds(70,30,80,10);
getContentPane().add(PIN);

txt2.setBounds(150,30,150,18);
getContentPane().add(txt2);


//shows Ok button
OKbtn.setBounds(230,60,70,30);
getContentPane().add(OKbtn);


//shows Cancel button
Can.setBounds(70,60,90,30);
getContentPane().add(Can);


setTitle("ATM");   //sets the title as ATM
setSize(400,130);  //sets the size
setVisible(true);  //makes our ATM visible

}

public static void main (String args[])
{
CodeGalaxy x = new CodeGalaxy();
}
}



Further explanation:

setBounds syntax:
variable.setBounds(x-axis,y-axis,width,height);

setSize syntax:
setSize(width, height);


public static void main (String args[])
{
Lab3 x = new Lab3();
}
without the public static void main, our program will run invisibly.

JTextField txt1 = new JTextField();
JTextField is a textbox with the variable name txt1


JLabel PIN = new JLabel("Pin: ");
JLabel is a label with the variable name PIN with the caption as Pin:


JButton Can = new JButton("Cancel");
JButton is a command button with the variable name Can with the caption as Cancel

Method Overloading


Whenever a two or more methods have the same name but different behaviors or parameters, it is called method overloading.

A good example of method overloading is a set (or a pair) of people with the same name. A very good example to understand this are social networking sites. Let's say that there are two people with the name Aphrodite Keys on Facebook. The first Aphrodite Keys is a famous celebrity, while the second is just a poser.

Between the two Aphrodite Keys, it is obvious that both have the same name. It is also obvious that both have different personalities and behaviors.  The original Aphrodite Keys posts updates regarding her work and insights of life honestly, while the poser Aphrodite Keys posts different things that may help gain her social network fame.

Given the codes below....

class CodeGalaxy
{
public int sum;

public CodeGalaxy()
{
sum = 0;
}

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

public void Add(int num1, int num2, int num3)
{
sum=int1+num2+num3;
}

public void Add(int num1)
{
sum = num1;
}
}

The code of the main class is the following:

public class UseGalaxy
{
public static void mai (String args[])
{
CodeGalaxy planet = new CodeGalaxy();
planet.Add(2,3);
planet.Add(1,2,3);
planet.Add(100);
}
}

Using the first planet.Add with parameters 2 and 3, the values are passed on the first (public void) Add in your object. The values of the second planet.Add with parameters 1,2 and 3, are passed on the second (public void) Add in your object. The last planet.Add with 1 as its parameter is passed on the last method in your object.

The main idea is: You cannot pass planet.Add(2,3)  to the second method in your object with public void Add(int1, int2, int3) since planet.Add has only two values and the method requires three values. Therefore, in order to use planet.Add(2,3), the values are passed on the first method with public void Add(int1,int2)

Parameters and Polymorphism

Parameters
A parameter is a special variable that are used as a subroutine to connect to another piece of an inputted data in that subroutine. Some programming languages refer parameters as arguments. There are two kinds of parameters: formal parameter and actual parameter.


Formal Parameter
Formal parameters are actually any kinds of variables placed inside a parenthesis. In the example below, the formal parameters are num1 and num2

class CodeGalaxy
{
public int sum;

public CodeGalaxy()
{
sum = 0;
}

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


Actual Parameters
An actual parameter is the value of the formal parameter. In the example below, the actual parameters are 2 and 3. The values of the actual parameter are passed to the formal parameter. If you refer to the codes above (formal) and the codes below (actual), 2 is passed to the formal parameter num1, while 3 is passed to the formal parameter num2.


public class UseGalaxy
{
public static void mai (String args[])
{
CodeGalaxy planet = new CodeGalaxy();
planet.Add(2,3);
}
}



Polymorphism
Polymorphism originated from the Greek word poly which means many, and morph which means form. Therefore, polymorphism means many forms. In programming, polymorphism is a variable, function, or (commonly) an object that has many forms. The main purpose of polymorphism in programming is for creating one name that can be used for a general class. Method Overriding and Method Overloading is a type of Polymorphism.

For more polymorphism, see next post (Method Overloading and Method Overriding)

Packages (Java)

What is a Package?


Java allows us to group classes in a collection, known as the Package.


A package is a helpful tool in organizing our work as well as separating our work from the libraries of codes made by others.

The standard Java library is known to have distributed over a number of packages, including the following:


  • java.util
  • java.lang
  • java.net
Reason for Using Packages


The purpose of using packages is to guarantee the uniqueness of class names. Two junior programmers, for example, come up with a good idea of supplying a price class. As long as the two programmers place their class in different packages, there is nothing wrong with it.

The sole purpose of package nesting is to manage their unique names. From the point of view of the complier, there is absolutely no relationship between nested packages. Similar to the packages java.util and java.util.jar both have nothing to do with each other since each has its own independent collection of classes.


Using Packages


A class can use all classes from its own package, including all public classes from other packages. There are indeed two ways to access public class, and those are the following:

1. Add the full package name in front of every class name

java.util.Date today = new java.util.Date();


2. The import keyword

import java.io.*;



The IMPORT keyword


The import statement gives you a shorthand to refer classes in the package. Once you use it, yo no longer have to give the classes their full names.

The * symbol is only used to import a single package. It makes you import the whole package itself.

Order of Precedence for Java Operators

Similar to Mathematics' PEMDAS or MDAS, Java also has its own Order of Precedence which is to be followed when understanding, creating or reading Java programs. It is a way for Java to determine which operator should it evaluate first before the others.

Below is the Order of Precedence displayed from the highest to the lowest precedence:


Priority  Operator  Use
1[ ]index of arrays

( )calling methods

.access members
2++increment

--decrement

+, -unary add, subtract

~NOT (bitwise)

!NOT (boolean / logical)

(type)new type cast

(new)new object
3*, /, %multiplication, division, modulo (remainder)
4+, - addition, subtraction 

+concatination
5<<signed bit shift left

>>signed bit shift right

>>>unsigned bit shift right
6<, <=less than, less than or equal to

>, >=greater than, greater than or equal to

instanceofcalling/testing references
7= =is equal to

! =is not equal to
8&AND (bitwise and logical)
9^XOR (bitwise and logical)
10|OR (bitwise and logical)
11&&Boolean AND
12||Boolean OR
13?, , , :conditional statements
14=assignment

*=, /=, +=, -=combinated assignment

%=combinated assignment

<<=, >>=combinated assignment

&=,^=, |=combinated assignment


Reminder:
  • Expressions within the parenthesis are first to be evaluated
  • Nested Parenthesis are evaluated from the inner to the outer parenthesis.
  • Higher precedence are done first before the lower precedence.

Stacks and Queues in Java

The stack and the queue is defined by two basic operations: insert a new item, and remove an item.



Representing stacks and queues with arrays is a natural idea. The rule used for a queue is to always remove the item that has been in the collection the most amount of time. This policy is known as first-in-first-out or FIFO. The rule used for a stack is to always remove the item that has been in the collection the least amount of time. This policy is known as last-in first-out or LIFO.

In stacking, we name the stack insert method push() and the stack remove operation pop(). When we queue, we name the insert method enqueue() and the remove dequeue().

Here's an exercise we just did in school today though it's quite complicated, i just wanna share the codes. It's about push(inserting) and pop(deleting) for the stack; as well as enqueue(inserting) and dequeue(deleting). Download the codes below:







It's important to download all three files.

What is the use of Compiling in Java?


 Here's a diagram of Computer Languages.

Machine language is all it starts since our computer can only read numbers 1 and 0. Then there goes Low-level languages, where a very good example is Assembly language and the C programming (language. Then there is High-level language, where you can find Visual Basic and Java.


So what's the use of Compiling in Java? Why can't you not run the program right away without compiling?

Because Java is one of the High-level languages, it translates it to a low level language and finally, machine language since as said earlier that our computer can only read binary digits.



So that means that the codes we type and the variables we create are translated to a language which the computer can only understand.

We cannot understand Machine Language immediately. It takes time to understand each line of Machine Language since each 1 and 0 has its own designated meaning depending on how we code it.

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.

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.

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.

Extended Search

Custom Search
Hello World