Você está na página 1de 32

File Name: Array.

java
Terminal No: 9
Programmer: Delos Reyes, Jose Mari Luis C.
Date and Time Created: Thursday, July 26, 2007, 11:10:50 AM
Description: This program uses array
Output: Multiplying a number to itself with out using input
stream reader

Program:

public class Array{


public static void main(String[] args){
int [] A = new int [5];
int [] B = new int [5];
for (int x=0; x<A.length; ++x){
A[x] = Integer.parseInt(args[x]);
B[x] = A[x] * A[x];
System.out.println(B[x]);
}
}
}
File Name: Array2.java
Terminal No: 9
Programmer: Delos Reyes, Jose Mari Luis C.
Date and Time Created: Thursday, June 28, 2007, 11:01:12 AM
Description: This program uses array
Output: multiplying a number to itself

Program:

import java.io.*;

public class Array2{

public static void main(String[] args) throws


IOException{
InputStreamReader isr = new
InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
int[] A = new int[5];
int[] B = new int[5];
String s;
for(int x=0; x<A.length;++x){
System.out.print("Enter" + (x+1) + "number: ");
s = br.readLine();
A[x] = Integer.parseInt(s);
}
System.out.println();

for(int x=0;x<A.length;++x){
B[x] = A[x] * A[x];
System.out.println(B[x]);
}
}
}
File Name: Array3.java
Terminal No: 9
Programmer: Delos Reyes, Jose Mari Luis C.
Date and Time Created: Thursday, June 21, 2007, 1:23:23 PM
Description: This program combined InputStreamReader and
BufferedReader in one line
Output: multiplying a number to itself

Program:

import java.io.*;

public class Array3{

public static void main(String[] args) throws


IOException{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
int[] A = new int[5];
int[] B = new int[5];
String s;
for(int x=0; x<A.length;++x){
System.out.print("Enter " + (x+1) + " number: ");
A [x] = Integer.parseInt(br.readLine());
}
System.out.println();

for(int x=0;x<A.length;++x){
B[x] = A[x] * A[x];
System.out.println(B[x]);
}
}
}
File Name: SwitchTest.java
Terminal No: 9
Programmer: Delos Reyes, Jose Mari Luis C.
Date and Time Created: Thursday, July 05, 2007, 1:04:22 PM
Description:
Output: Displaying a number

Program:

public class SwitchTest{

public static void main(String args[]){

int KeyValue = 1;
switch(KeyValue){

case 1:
System.out.println("one");
break;

case 2:
System.out.println("two");
break;

case 3:
System.out.println("three");
break;

default:
System.out.println("more");
break;

}
}
}
File Name: Sample.java
Terminal No: 9
Programmer: Delos Reyes, Jose Mari Luis C.
Date and Time Created: Thursday, July 05, 2007, 1:04:22 PM
Description: This program uses two sub-class to diplay a
message
Output:

Program:

public class Sample{


public static void displayMessage(String st){
System.out.println("\n" + "This message is
all about numbers: "+ st);
}

public static void main(String[] args){


Sample sample = new Sample();
sample.displayMessage("\n" + "\n" +
" Hitchyfreaks@yahoo.com" + "\n" +
" JM | Kamikuto" +
"\n" + "\n" +
" one" + "\n" +
" two" + "\n" +
" three" + "\n" +
" four" + "\n" +
"\n" + "\n" +
" JM | Kamikuto" + "\n" +
" Hitchyfreaks@yahoo.com");
}
}
File Name: Month.java
Terminal No: 9
Programmer: Delos Reyes, Jose Mari Luis C.
Date and Time Created: Thursday, June 28, 2007, 11:45:41 AM
Description:
Output: Displaying months in proper order

Program:

public class Month{

public static void main(String args[]){

String[] month =
{"January","February","March","April"};
for(int i = 0;i<month.length;++i){
System.out.println(month[i]);

}
}
}
File Name: Month2.java
Terminal No: 9
Programmer: Delos Reyes, Jose Mari Luis C.
Date and Time Created: Thursday, June 28, 2007, 11:53:38 AM
Description:
Output:

Program:

public class Month2{

public static void main(String args[]){


//String[] month={"Jan","Feb","Mar","Apr"}
int[] month = {1,2,3,4,5};
for (int i=0;i<month.length;++i){
System.out.println(month[i]);
}
}
}
File Name: Volume1.java
Terminal No: 9
Programmer: Delos Reyes, Jose Mari Luis C.
Date and Time Created: Thursday, June 28, 2007, 12:28:10 PM
Description:
Output: Displaying the volume of radius and height

Program:

import java.io.*;

public class Volume1{

public static void main(String args[])throws


java.io.IOException{
InputStreamReader isr = new
InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
double volume,radius,height;
String output;
final double PI = 3.1416;

System.out.print("Enter radius: ");


radius = Double.parseDouble(br.readLine());

System.out.print("Enter Height: ");


height = Double.parseDouble(br.readLine());

volume = PI * radius * radius * height;

output ="For a cylinder of radius" + radius;


output +="and a height of" + height;
output +="\nthe volume is" + volume;

System.out.println(output);
}
}
File Name: Kamikuto1.java
Terminal No: 9
Programmer: Delos Reyes, Jose Mari Luis C.
Date and Time Created: Thursday, July 05, 2007, 1:44:01 PM
Description: This program uses Switch Statements and
Multiple Sub-Classes to covert numbers to words
Output: Converting numbers to words

Program:

public class Kamikuto1{

private double getPlace( String number ){


switch( number.length() ){

case 1:
return DefinePlace.UNITS;
case 2:
return DefinePlace.TENS;
case 3:
return DefinePlace.HUNDREDS;
case 4:
return DefinePlace.THOUSANDS;
case 5:
return DefinePlace.TENTHOUSANDS;
case 6:
return DefinePlace.MILLIONS;
//return DefinePlace.LAKHS;
case 7:
return DefinePlace.TENMILLIONS;
//return DefinePlace.TENLAKHS;
case 8:
return DefinePlace.BILLIONS;
//return DefinePlace.CRORES;
case 9:
return DefinePlace.TENBILLIONS;
//return DefinePlace.TENCRORES;
}//switch
return 0.0;
}// getPlace

private String getWord( int number ){


switch( number ){
case 1:
return "One";
case 2:
return "Two";
case 3:
return "Three";
case 4:
return "Four";
case 5:
return "Five";
case 6:
return "Six";
case 7:
return "Seven";
case 8:
return "Eight";
case 9:
return "Nine";
case 0:
return "Zero";
case 10:
return "Ten";
case 11:
return "Eleven";
case 12:
return "Twelve";
case 13:
return "Thirteen";
case 14:
return "Forteen";
case 15:
return "Fifteen";
case 16:
return "Sixteen";
case 17:
return "Seventeen";
case 18:
return "Eighteen";
case 19:
return "Ninteen";
case 20:
return "Twenty";
case 30:
return "Thirty";
case 40:
return "Forty";
case 50:
return "Fifty";
case 60:
return "Sixty";
case 70:
return "Seventy";
case 80:
return "Eighty";
case 90:
return "Ninty";
case 100:
return "Hundred";
} //switch
return "";
} //getWord

private String cleanNumber( String number ){


String cleanedNumber = "";

cleanedNumber = number.replace( '.', ' ' ).


replaceAll( " ", "" );
cleanedNumber = cleanedNumber.replace( ',', '
' ).replaceAll( " ", "" );
if( cleanedNumber.startsWith( "0" ) )
cleanedNumber = cleanedNumber.replaceFirst( "0",
"" );

return cleanedNumber;
} //cleanNumber

public String convertNumber( String number ){


number = cleanNumber( number );
double num = 0.0;
try{
num = Double.parseDouble( number );
}catch( Exception e ){
return "Invalid Number Sent to Convert";
} //catch

String returnValue = "";


while( num > 0 ){
number = "" + (int)num;
double place = getPlace(number);

if( place == DefinePlace.TENS || place ==


DefinePlace.TENTHOUSANDS || place ==
DefinePlace.TENMILLIONS || place == DefinePlace.TENBILLIONS
){
//if( place == DefinePlace.TENS || place ==
DefinePlace.TENTHOUSANDS || place ==
//DefinePlace.TENMILLIONS || place ==
DefinePlace.TENCRORES ){
int subNum = Integer.parseInt( number.charAt(0) + "" +
number.charAt(1) );

if( subNum >= 21 && (subNum%10) != 0 ){


returnValue += getWord( Integer.parseInt( "" +
number.charAt(0) ) * 10 ) + " " + getWord( subNum%10 ) ;
} //if
else{
returnValue += getWord(subNum);
}//else

if( place == DefinePlace.TENS ){


num = 0;
}//if
else if( place == DefinePlace.TENTHOUSANDS ){
num -= subNum * DefinePlace.THOUSANDS;
returnValue += " Thousand ";

}//if
else if( place == DefinePlace.TENMILLIONS ){
num -= subNum * DefinePlace.MILLIONS;
returnValue += " Million ";
}//if
else if( place == DefinePlace.TENBILLIONS ){
num -= subNum * DefinePlace.BILLIONS;
returnValue += " Billion ";

//}//if
//else if( place == DefinePlace.TENLAKHS ){
//num -= subNum * DefinePlace.LAKHS;
//returnValue += " Lakhs ";
//}//if
//else if( place == DefinePlace.TENCRORES ){
//num -= subNum * DefinePlace.CRORES;
//returnValue += " Crores ";

}//if
}//if
else{
int subNum = Integer.parseInt( "" + number.charAt(0) );

returnValue += getWord( subNum );


if( place == DefinePlace.UNITS ){
num = 0;
}//if
else if( place == DefinePlace.HUNDREDS ){
num -= subNum * DefinePlace.HUNDREDS;
returnValue += " Hundred ";
}//if
else if( place == DefinePlace.THOUSANDS ){
num -= subNum * DefinePlace.THOUSANDS;
returnValue += " Thousand ";

}//if
else if( place == DefinePlace.MILLIONS ){
num -= subNum * DefinePlace.MILLIONS;
returnValue += " Million ";
}//if
else if( place == DefinePlace.BILLIONS ){
num -= subNum * DefinePlace.BILLIONS;
returnValue += " Billion ";

//}//if
//else if( place == DefinePlace.LAKHS ){
//num -= subNum * DefinePlace.LAKHS;
//returnValue += " Lakh ";
//}//if
//else if( place == DefinePlace.CRORES ){
//num -= subNum * DefinePlace.CRORES;
//returnValue += " Crore ";

}//if
}//else
}//while
return returnValue;
}//convert number

public static void main( String args[] ){


Kamikuto1 cv = new Kamikuto1();

if( args.length >= 1 )


{
for( int i=0; i<args.length; i++ )
System.out.println( "Given Number : " + args[i] +
"\nConverted: " + cv.convertNumber(args[i]) + "\n\n" );
System.exit(0);
}

System.out.println( "Given Number :


999999999\nConverted: " + cv.convertNumber("999999999") +
"\n\n" );
}//main
} //class
class DefinePlace{
public static final double UNITS = 1;
public static final double TENS = 10 * UNITS;
public static final double HUNDREDS = 10 * TENS;
public static final double THOUSANDS = 10 * HUNDREDS;
public static final double TENTHOUSANDS = 10 *
THOUSANDS;
public static final double MILLIONS = 10 *
TENTHOUSANDS;
public static final double TENMILLIONS = 10 * MILLIONS;

public static final double BILLIONS = 10 * TENMILLIONS;


public static final double TENBILLIONS = 10 * BILLIONS;

//public static final double LAKHS = 10 * TENTHOUSANDS;


//public static final double TENLAKHS = 10 * LAKHS;
//public static final double CRORES = 10 * TENLAKHS;
//public static final double TENCRORES = 10 * CRORES;
} //class

File Name: Human.java


Terminal No: 9
Programmer: Delos Reyes, Jose Mari Luis C.
Date and Time Created: Thursday, August 02, 2007, 11:05:42
AM
Description: This program uses inheritance
Output:

Program:

public class Human{


public static void main(String[] args){
Human human = new Human();
Cat cat = new Cat();
Dog dog = new Dog();
call(dog);
call(cat);
}

public static void call(Animal animal){


animal.cry();
}
}

File Name: Dog.java


Terminal No: 9
Programmer: Delos Reyes, Jose Mari Luis C.
Date and Time Created: Thursday, August 02, 2007, 11:05:42
AM
Description:
Output:

Program:

public class Dog extends Animal{


public void cry(){
System.out.println("\n" + " Cries:" +
"\n" + " AW!!" +
"\n" + " AW!!" +
"\n" + " AW!!");
}
}

File Name: Cat.java


Terminal No: 9
Programmer: Delos Reyes, Jose Mari Luis C.
Date and Time Created: Thursday, August 02, 2007, 11:05:42
AM
Description:
Output:

Program:

public class Cat extends Animal{


public void cry(){
System.out.println("\n" + " Cries:" +
"\n" + " MEOW!!" +
"\n" + " MEOW!!" +
"\n" + " MEOW!!");
}
}

File Name: Animal.java


Terminal No: 9
Programmer: Delos Reyes, Jose Mari Luis C.
Date and Time Created: Thursday, August 02, 2007, 11:05:42
AM
Description:
Output:

Program:

public class Animal{


public void run(){
System.out.println("Run!!!");
}

public void cry(){


System.out.println("Cry!!!");
}
}

File Name: Kamikuto.java


Terminal No: 9
Programmer: Delos Reyes, Jose Mari Luis C.
Date and Time Created: Thursday, August 02, 2007, 11:54:07
AM
Description:
Output:

Program:

//this program shows all my favorites. music that i am


listening,
//music that i admire, and persons that i idolized when it
comes to music
//or guitar playing.

public class Kamikuto{


public static void main(String[] args){
Kamikuto kamikuto = new Kamikuto();
One one = new One();
Two two = new Two();
Three three = new Three();
Four four = new Four();
call(one);
call(two);
call(three);
call(four);
}

public static void call(Kuto kuto){


kuto.favorites();
}
}

File Name: One.java


Terminal No: 9
Programmer: Delos Reyes, Jose Mari Luis C.
Date and Time Created: Thursday, August 02, 2007, 11:05:42
AM
Description:
Output:

Program:

public class One extends Kuto{


public void favorites(){
System.out.println("\n"
+ "----------
Hitchyfreaks@yahoo.com----------" + "\n" + "\n"
+ " * Favorite Music Instrument:" + "\n"
+ "\n" + " Jazz"
+ "\n" + " Reggae"
+ "\n" + " Rock"
+ "\n" + " Funky"
+ "\n" + " Classical"
+ "\n" + " Fusion Rock"
+ "\n"
+ "\n" +
"----------------------------------------");
}
}

File Name: Two.java


Terminal No: 9
Programmer: Delos Reyes, Jose Mari Luis C.
Date and Time Created: Thursday, August 02, 2007, 11:05:42
AM
Description:
Output:

Program:

public class Two extends Kuto{


public void favorites(){
System.out.println("\n" + " * Favorite
Music Instrument:"
+ "\n" + "\n" + " Guitar"
+ "\n" + " Bass"
+ "\n"
+ "\n" +
"---------------------------------------------");
}
}

File Name: Three.java


Terminal No: 9
Programmer: Delos Reyes, Jose Mari Luis C.
Date and Time Created: Thursday, August 02, 2007, 11:05:42
AM
Description:
Output:

Program:

public class Three extends Kuto{


public void favorites(){
System.out.println("\n" + " * Favorite
Band:"
+ "\n" + "\n" + " Bamboo"
+ "\n" + " G3"
+ "\n" + " Racer X"
+ "\n" + " Nitro"
+ "\n" + " Rage Against The
Machine"
+ "\n" + " Red Hot Chilli Peppers"
+ "\n" + " P.O.T"
+ "\n" + " 311"
+ "\n" + " Dream Theater"
+ "\n" + " Audioslave"
+ "\n" + " Mr.Big");
}
}

File Name: Four.java


Terminal No: 9
Programmer: Delos Reyes, Jose Mari Luis C.
Date and Time Created: Thursday, August 02, 2007, 11:05:42
AM
Description:
Output:

Program:

public class Four extends Kuto{


public void favorites(){
System.out.println("\n"
+
"--------------------------------------------" + "\n" + "\n"
+ " * Favorite Guitarist and Bassist"
+ "\n" + "\n" + " John Petrucci
[ Dream Theater, g3 ]"
+ "\n" + " Michael Angelo Batio
[ Nitro Band ]"
+ "\n" + " Steve Vai [ g3 ]"
+ "\n" + " Victor Wooten - solo
instrumental artist( bassist )"
+ "\n" + " Paul Gilbert [ Mr.Big,
Racer X ]"
+ "\n" + " Joe Satriani [ g3 ]"
+ "\n" + " Eric Johnson [ g3 ]"
+ "\n" + " Tuck Andress
[ Classical ] - solo instrumental artist"
+ "\n" + " Greg Howe - solo
instrumental artist, sessionist"
+ "\n" + " Guthrie Govan - solo
instrumental artist"
+ "\n"
+ "\n" +
"----------------------------------------");
}
}

File Name: While.java


Terminal No: 9
Programmer: Delos Reyes, Jose Mari Luis C.
Date and Time Created: Thursday, July 28, 2007
Description:
Output:

Program:

import javax.swing.*;

public class While{


public static void main(String[] args){
final int MAXNUM = 4;
String message = "This program will ask you to enter
" + MAXNUM
+ " numbers.";

JOptionPane.showMessageDialog(null,message,"While
Loop",
JOptionPane.INFORMATION
_MESSAGE);

double total=0;
int count=1;
String msg=null;
while(count <= MAXNUM){
switch(count){
case 1:
msg = "First";
break;
case 2:
msg = "Second";
break;
case 3:
msg = "Third";
break;
case 4:
msg = "Fourth";
break;
}

String s = JOptionPane.showInputDialog("Enter " +


msg + " Number: ");
double num = Double.parseDouble(s);

total +=num;
++count;
}
JOptionPane.showMessageDialog(null,"The total of the
" + MAXNUM + " numbers is " + total,
"Result",JOptionPane.IN
FORMATION_MESSAGE);
System.exit(0);

}
}
File Name: Kuto.java
Terminal No: 9
Programmer: Delos Reyes, Jose Mari Luis C.
Date and Time Created: Thursday, August 02, 2007, 11:05:42
AM
Description:
Output:

Program:

public class Kuto{


public void favorites(){
System.out.println("Favorites");
}
public void hobbies(){
System.out.println("Hobbies");
}
}
What is Java Arrays?

(For Array.java, Array2.java, Array3.java)

Structure of Java Arrays


The Java array depicted above has 7 elements. Each element
in an array holds a distinct value. In the figure, the
number above each element shows that element's index.
Elements are always referenced by their indices. The first
element is always index 0. This is an important point, so I
will repeat it! The first element is always index 0. Given
this zero-based numbering, the index of the last element in
the array is always the array's length minus one. So in the
array pictured above, the last element would have index 6
because 7 minus 1 equals 6.

Java Array Declaration


An array variable is declared the same way that any Java
variable is declared. It has a type and a valid Java
identifier. The type is the type of the elements contained
in the array. The [] notation is used to denote that the
variable is an array. Some examples:

Java Array Initialization


Once an array variable has been declared, memory can be
allocated to it. This is done with the new operator, which
allocates memory for objects. (Remember arrays are implicit
objects.) The new operator is followed by the type, and
finally, the number of elements to allocate. The number of
elements to allocate is placed within the [] operator.

What is Inheritance?

(For Human.java(Main), Cat.java, Dog.java, Animal.java,


Kamikuto.java(Main), One.java, Two.java, Three.java,
Four.java, Kuto.java)
Inheritance syntax
Inheritance is such an integral part of Java (and OOP
languages in general) that it was introduced in Chapter 1
and has been used occasionally in chapters before this one
because certain situations required it. In addition, you’re
always doing inheritance when you create a class, because
if you don’t say otherwise you inherit from Java’s standard
root class Object.
The syntax for composition is obvious, but to perform
inheritance there’s a distinctly different form. When you
inherit, you say “This new class is like that old class.”
You state this in code by giving the name of the class as
usual, but before the opening brace of the class body, put
the keyword extends followed by the name of the base class
. When you do this, you automatically get all the data
members and methods in the base class.

What is Buffered Reader?

(For Volume1.java)

Read text from a character-input stream, buffering


characters so as to provide for the efficient reading of
characters, arrays, and lines.

The buffer size may be specified, or the default size may


be used. The default is large enough for most purposes.

In general, each read request made of a Reader causes a


corresponding read request to be made of the underlying
character or byte stream. It is therefore advisable to wrap
a BufferedReader around any Reader whose read() operations
may be costly, such as FileReaders and InputStreamReaders.
For example,

BufferedReader in
= new BufferedReader(new FileReader("foo.in"));

will buffer the input from the specified file. Without


buffering, each invocation of read() or readLine() could
cause bytes to be read from the file, converted into
characters, and then returned, which can be very
inefficient.

Programs that use DataInputStreams for textual input can be


localized by replacing each DataInputStream with an
appropriate BufferedReader.
What is Input Stream Reader?

(For Volume1.java)

An InputStreamReader is a bridge from byte streams to


character streams: It reads bytes and decodes them into
characters using a specified charset. The charset that it
uses may be specified by name or may be given explicitly,
or the platform's default charset may be accepted.

Each invocation of one of an InputStreamReader's read()


methods may cause one or more bytes to be read from the
underlying byte-input stream. To enable the efficient
conversion of bytes to characters, more bytes may be read
ahead from the underlying stream than are necessary to
satisfy the current read operation.

For top efficiency, consider wrapping an InputStreamReader


within a BufferedReader. For example:

BufferedReader in
= new BufferedReader(new InputStreamReader(System.in));

What is Java Switch Statements?

(For Switchtest.java)

The switch statement in Java provides a convenient method


for branching a program based on a number of conditionals.
This recipe describes the use of the Java switch statement.

In computer programming, a switch statement is a type of


control statement that exists in most modern imperative
programming languages (e.g., C, C++, C#, and Java). Its
purpose is to allow the value of a variable or expression
to control the flow of program execution. In some other
programming language, a statement that is syntactically
different but conceptually the same as the switch statement
is known as a case statement or a select statement.

In most languages, a switch statement is defined across


many individual statements. A typical syntax is that the
first line contains the actual word "switch" followed by
either the name of a variable or some other expression
allowed by the language's syntax. This variable or
expression is usually referred to as the "control variable"
of the switch statement. After this line, following lines
define one or more blocks of code that represent possible
branches that program execution may take.

Each block begins with a line containing the case keyword


followed a value that the control variable may have. If the
value of the control variable matches this value, program
execution will jump to that block of code. If not, the
value specified in the next block (if present) is examined
and the process repeats.

An optional special block is also allowed, which does not


specify any value and which begins with the default keyword
instead of the case keyword. If this block is present and
if none of the values listed for any other block matches
that of the control variable, program execution will jump
to the statement following the default keyword.

The method of terminating a block is also of note.


Typically, a break keyword is used to signal the end of the
block. When encountered, this keyword causes program
execution to continue with the first statement after the
series of statements within the switch statement, thus
completing execution of the switch statement. If no break
keyword is present at the end of the block, in many
languages program execution "falls through" to the code
associated with the next block in the switch statement, as
if its value also matched the value of the control
variable. Notable exceptions include C#, in which
fallthrough is not permitted unless the block is empty and
all blocks must be terminated via a break, or by using
another keyword. Similarly, almost all BASIC dialects that
feature this type of statement do not allow fallthrough.

What is While and do-While Statements?

(For While.java)

The while and do-while Statements


The while statement continually executes a block of
statements while a particular condition is true. Its syntax
can be expressed as:
while (expression) {
statement(s)
}
The while statement evaluates expression, which must return
a boolean value. If the expression evaluates to true, the
while statement executes the statement(s) in the while
block. The while statement continues testing the expression
and executing its block until the expression evaluates to
false. Using the while statement to print the values from 1
through 10 can be accomplished as in the following WhileDemo
program:
class WhileDemo {
public static void main(String[] args){
int count = 1;
while (count < 11) {
System.out.println("Count is: " + count);
count++;
}
}
}

You can implement an infinite loop using the while


statement as follows:

while (true){
// your code goes here
}

The Java programming language also provides a do-while


statement, which can be expressed as follows:

do {
statement(s)
} while (expression);
The difference between do-while and while is that do-while
evaluates its expression at the bottom of the loop instead
of the top. Therefore, the statements within the do block
are always executed at least once, as shown in the
following DoWhileDemo program:
class DoWhileDemo {
public static void main(String[] args){
int count = 1;
do {
System.out.println("Count is: " + count);
count++;
} while (count <= 11);
}
}

Você também pode gostar