Tweet

Javada nesnesel yaklaşım


Kaldığımız yer olan javanın nesnesel yaklaşım konusu ile devam edelim.Java için her şey nesneden ibarettir.Java öne sunulan sorunu nesnesel platformda algılamalıdır.Yazacağınız kodları bu düzeyde düşünmelisiniz.Bu gün bir problem belirleyip bu problemi nesnesel yaklaşımla çözmeye çalışacağız.[...]

Farzedelimki bizden bir birim çevirici programı yazmamız istendi.Bilinem uzunluk birimleri feet,inch,yard,mile.Bu brimller arasında çevirim yapılacak.Verilmiş bir birimi istenilen birime çevirmemiz lazım.Başta bunu yapmak için kullanıcıya bir menu sunup bu menuden ne yapmak istediğini seçtirip ona göre işlem yapmalıyız.

Probleme nesnesel yaklaşırsak eğer size tavsiyem problemdeki isim ve fiillerin altını çizmeniz olacaktır.Çünkü her fiil sizin için bir method,her isim de sizin için bir sınıf ve ya bir özellik olacaktır.Bu problemde görüldüğü üzere uzunluk ,inches,feet,yard,mile gibi isimler bulunmakta ve çevirmek diye de bir fiil.Şimdi baştan başlarsak eğer program tasarımına bağlı olarak programcı isterse yazacağı programı binlerce küçük sınıfa bölebilir.Ben bu kodda Measurement diye bir genel sınıf ouluşturup iki tane özellik koymaya karar verdim.Bu özellikler bir matematiksel büyüklük(measurement) ve uzunluğun birimi (unit).Yine bu sınıf içinde dönüşümleri yapıp kullanıcıya sundum.Bunun yanı sıra menu sunma işinde yeniden bir sınıf oluşturdum.Menunün içeriğini bir dizi şeklinde alıp sira ile bastırdım.Menu işi main de de yapılabilirdi belki ama size tavsiyem yazdığınız kodların tekrar kullanılabilmesi olmalıdır.Şimdi size Measurement sınıfını kod olarak vereyim;

CODE:
/**
* THis class heps user to create an Object and display the
* information about measurement.
* thecoders.net
*/
/****************************************************************************************************************************************************/
package measurements;
//===================================================================
import java.text.NumberFormat; //The NUmberFormat class for output
//===================================================================
public class Measurements {
private double measurements; //Instance attributes
private String unit;
//==============================================================
public Measurements(){ //Default constructor

}
//=============================================================
public Measurements(double measurements,String unit){ //Specified constructor
this.measurements = measurements; //Assign the measurement
this.unit = unit; //Assign the unit
}
//=============================================================
/**
* @return the measurements
*/
public double getMeasurements() {
return measurements; //Return the measurement
}
//============================================================
/**
* @param measurements the measurements to set
*/
public void setMeasurements(double measurements) {
this.measurements = measurements; //Assign the measurement
}
//============================================================
/**
* @return the unit
*/
public String getUnit() {
return unit; //Return the unit
}
//===========================================================
/**
* @param unit the unit to set
*/
public void setUnit(String unit) {
this.unit = unit; //Assign the unit
}
//==========================================================
/**Set the unit by using the unitSelection*/
public void setUnit(int choice){
if(choice == 1) //If user's input equal to 1
this.unit = "inches"; //Set the unit inches
else if(choice == 2) //If user's input equal to 2
this.unit = "feet"; //Set the unit feet
else if(choice == 3) //If user's input equal to 3
this.unit = "yard"; //Set the unit yard
else if (choice == 4) //If user's input equal to 4
this.unit = "mile"; //Set the unit mile
}
//===========================================================
/**Convert the entered measurement into Inches*/
public void Inches(){

double result; //For converted measurement

if(this.unit.equals("inches")){ //Control if the units are equal
System.out.println("nThe unit is already in inches!!!"); //Display warning message
System.out.println("The measurement "+this.measurements //Display the same measurement and same unit
+" inches".toUpperCase()+"n");
}
else if(this.unit.equals("feet")){ //Control if the unit is feet
result = this.measurements * 12; //Convert into inches
toString(result,"inches"); //Display the result
}
else if(this.unit.equals("yard")){ //Control if the unit is yard
result = this.measurements * 36; //Convert into inches
toString(result,"inches"); //Display the result
}
else if(this.unit.equals("miles")){ //Control if the unit is miles
result = this.measurements * (12 * 5280); //Convert into inches
toString(result,"inches"); //Display the result
}
else //If no match prompt the user wrong unit selection
System.out.println("Wrong unit selection!!nTRy again please.");
}
//==========================================================
/**Convert the entered measurement into Feet*/
public void Feet(){
double result; //For converted measurement

if(this.unit.equals("feet")){ //Control if the units are equal
System.out.println("nThe unit is already in feet!!"); //Display warning message
System.out.println("The measurement "+this.measurements //Display the same measurement and same unit
+" feet".toUpperCase()+"n");
}
else if(this.unit.equals("inches")){ //Control if the unit is inches
result = this.measurements / 12; //Convert into feet
toString(result,"feet"); //Display the result
}
else if(this.unit.equals("yard")){ //Control if the unit is yard
result = this.measurements * 3; //Convert into feet
toString(result,"feet"); //Display the result
}
else if(this.unit.equals("mile")){ //Control if the unit is mile
result = this.measurements * 5280; //Convert into feet
toString(result,"feet"); //Display the result
}
else //If no match prompt the user wrong unit selection
System.out.println("Wrong unit selection!!nTRy again please.");
}
//====================================================
/**Convert the entered measurement into Yard*/
public void Yard(){
double result; //For converted measurement

if(this.unit.equals("yard")){ //Control if the units are equal
System.out.println("nThe unit is already in yard!!"); //Display warning message
System.out.println("The measurement "+this.measurements //Display the same measurement and same unit
+" yard".toUpperCase()+"n");
}
else if(this.unit.equals("inches")){ //Control if the unit is inches
result = this.measurements / 36; //Convert into yard
toString(result,"yard"); //Display the result
}
else if(this.unit.equals("feet")){ //Control if the unit is inches
result = this.measurements / 3; //Convert into yard
toString(result,"yard"); //Display the result
}
else if(this.unit.equals("mile")){ //Control if the unit is inches
result = this.measurements * 1760; //Convert into yard
toString(result,"yard"); //Display the result

}
else //If no match prompt the user wrong unit selection
System.out.println("Wrong unit selection!!nTRy again please.");
}
//====================================================
/**Convert the entered measurement into Yard*/
public void Mile(){

double result; //For converted measurement

if(this.unit.equals("mile")){ //Control if the units are equal
System.out.println("nThe unit is already in yard!!"); //Display warning message
System.out.println("The measurement "+this.measurements //Display the same measurement and same unit
+" mile".toUpperCase()+"n");
}
else if(this.unit.equals("inches")){ //Control if the unit is inches
result = this.measurements * 12 * 5280; //Convert into mile
toString(result,"mile"); //Display the result
}
else if(this.unit.equals("feet")){ //Control if the unit is inches
result = this.measurements / 5280; //Convert into mile
toString(result,"mile"); //Display the result
}
else if(this.unit.equals("yard")){ //Control if the unit is inches
result = this.measurements / 1760; //Convert into mile
toString(result,"mile"); //Display the result
}
else //If no match prompt the user wrong unit selection
System.out.println("Wrong unit selection!!nTRy again please.");
}
//===================================================
/**Display the result in string form via using NumberFormat class*/
public void toString(double value,String unit){

String output = " "; //Need for the result
String result;
int fractiondigit = 3; //Fraction digit
NumberFormat form = NumberFormat.getInstance();

form.setMaximumFractionDigits(fractiondigit); //Set the fraction digit as max.fractiondigit
form.setMinimumFractionDigits(fractiondigit); //Set the fraction digit as min.fractiondigit

result = form.format(value); //Change the form of the value

//Prepare the message in string form
output += "n**->The measurement that you enter "+this.measurements+" and as a unıt of "
+this.unit.toUpperCase()+"n **-> convert into the value of "+result+" and unit of "+unit.toUpperCase()+"nn";

System.out.println(output); //Prompt the user the result

}
//================================================================================================================================================
}
/***************************************************************THE END*******************************************************************************/


Kodda görüldüğü üzere NumberFormat kütüphanesi kullanılmıştır.Bu kütüphane sayılarınızın aynı digit büyüklüğünde olmasını sağlar.Gerektiği sürece kullanmanız sizin yararınıza olacaktır.

Şimdi yukarıda bahsettiğim Menu sınıfını oluşturalım,dediğim gibi yazacağınız kodları sadece burda değil bundan sonra yazacağınız kodlarda kullanabilir olmanız sizin yararınıza olacaktır.Kod aşağıdaki gibidir;

CODE:
package menu;

public class Menu {
//===============================================================
private int currentChoice; //Instance attributes
private String[] menuItems; //For menu items
//================================================================
/**Default constructor*/
public Menu(){

}
//================================================================
/**Specified constructor*/
public Menu(String[] menuItems){
this.menuItems = menuItems;
}
//=====================================================================
/**
* Uses for unit selection. Define the unitSelection
* static there is no need object reference
* */
public static void unitSelection(){

System.out.println("1-)For INCHES:"); //if unit is inches
System.out.println("2-)For FEET:"); //if unit is feet
System.out.println("3-)For YARD:"); //if unit is yard
System.out.println("4-)For MILE:"); //if unit is mile
System.out.print("Press the number to set unitnWhat is your unit ?");
}
//=====================================================================
/**
* Uses for display the menu items that
* user create via using the constructor.
* */
public void display(){
for(int i = 0; i < this.menuItems.length; i++)
System.out.println("n"+(i + 1) + "- " + this.menuItems[i]);
System.out.print("Press the number to convert into:");
}

//=======================================================================

/**
* @return the currentChoice
*/
public int getCurrentChoice() {
return currentChoice; //Return the currentChoise
}

/**
* @param currentChoice the currentChoice to set
*/
public void setCurrentChoice(int currentChoice) {
this.currentChoice = currentChoice; //Set the currentChoise
}
/**
* @return the menuItems
*/
public String[] getMenuItems() {
return menuItems;
}
/**
* @param menuItems the menuItems to set
*/
public void setMenuItems(String[] menuItems) {
this.menuItems = menuItems;
}
}
/*************************************THE END************************************************/


Yukarıdaki kodda menu ekrana bastırılıp kullanıcıdan seçim(currentChoice) yapması istenir.Seçilen işleme göre program yürütülür.

Sıra geldi bu programı test edeceğimiz main sınıfını oluşturmaya.Main sınıfı aşağıdaki gibi olacaktır;
CODE:
//=========================================================================================
package Testmeasurements; //Package name
//=========================================================================================
import java.util.Scanner;
import measurements.Measurements; //Import neccessary class
import menu.Menu;
//=========================================================================================
public class Testmeasurements {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("******************************************************");
System.out.println("**This program uses for converting the measurement****");
System.out.println("** into another unit such as feet,yard,mile,inches****");
System.out.println("******************************************************n");
//Create Scanner object
Scanner input = new Scanner(System.in); //Class for getting &Auml;&plusmn;nput
String reply; //Answer for go on or not
int unit; //For unit selection
//===================================================================================
do{
//===============================================================================
System.out.print("Enter the measurement value:");
double value = input.nextDouble(); //Get the measurement value from user

//===============================================================================
/**
* For menu selection there ara two ways taht we can deal with;
* first we can write a specific menu for only measurement class
* but we are told that we have to reuse menu in class where we need menuSelection
* for that reason I use not only specified menuSelection but also
* a menuSelection whose menuItems can be arrange by user.As an example
* this can help to user to create menuItems for any program where we need
* a menuSelection we can reaarrange the menuItems
* String[] menuItems ={"For Inches:", "For Feet:","For Yard:","For Mile:"};
* Menu menu = new Menu(menuItems);
*
*/
System.out.println("To choose the unit of value press the number:");
do {
Menu.unitSelection(); //Menu class static unit selection
System.out.print("nEnter the number to set unit:"); //Prompt the user what to do

unit = input.nextInt(); //Get the unit from user
if(unit < 1 || unit > 4) //Check the unit if it is valid or not
System.out.println("Invalid unit selection!!nTry again plaese."); //Display warning message
}while(unit < 1 || unit > 4); //Repeat it until valid unit is entered

//================================================================================
/*
* Another way of creating object is using specified const.
* but it is really bad about controlling the parameter
* for that reason we are told that while creating object
* we have to use default const. and for setting variables
* we must use the setter method.
*/

Measurements measurements = new Measurements(); //Crate an object via using default constructor
measurements.setMeasurements(value); //Set the value by using setter method of measurement class
measurements.setUnit(unit); //Set the unit by using setter method of measurement class

//================================================================================
String[] menuItems ={"For Inches:", "For Feet:","For Yard:","For Mile:"};//Define menu items
Menu menu = new Menu(menuItems); //Creating menu object using specified constructor.
do {

menu.display(); //Displey the menu items
menu.setCurrentChoice(input.nextInt()); //Get the cchoice from user
if(menu.getCurrentChoice() < 1 || menu.getCurrentChoice() > 4) //Control it if it is valid
System.out.println("Invalid operation selection!!nTry again please."); //Prompt warning message
}while(menu.getCurrentChoice() < 1 || menu.getCurrentChoice() > 4 ); //Do it until valid choice is entered
//=============================================================================

switch(menu.getCurrentChoice()){
/******************************************************************************/

case 1: //If user want to convert to inches
measurements.Inches(); //Call Inches method from measurement class
break;
//=========================================================================

case 2: //If user want to convert to feet
measurements.Feet(); //Call Feet method from measurement class
break;
//==========================================================================

case 3: //If user want to convert to yard
measurements.Yard(); //Call Yard method from measurement class
break;
//==========================================================================

case 4: //If user want to convert to mile
measurements.Mile(); //Call Mile method from measurement class
break;
//==========================================================================

default: //If no match promt the user invalid selection
System.out.println("Invalid selection!!");
}
//================================================================================

System.out.println("Do you want to continue ?(Y-y && N - n)"); //If user wants to go on ?
System.out.print("To continue press Y or y :");
reply = input.next(); //Get the answer
reply = reply.toUpperCase(); //Convert the uppercase
//================================================================================

}while(reply.equals("Y")); //Do the operation if Y is entered

//====================================================================================

if(!reply.equals("Y")) //If reply isn't equal to Y display goodbyee message
System.out.println("By byeee");
//====================================================================================
}
}
/************************************************************************THE END**********************************************************************/


Şimdilik burda kalaım ilerleyen zamanda bu konu üzerine bir kaç alıştırma daha yapmayı planlıyorum.Javada nesnesel yaklaşım çok önemlidir.Öğrenmek açısından size tavsiyem yazılmış oln kodları çalıştırıp denemeniz olacaktır.Umarım sizin için faydalı kodlar olmuştur.







seyhan

12 Kasim 2007 15:21

İlgili Olabilecek Makaleler


Yorumlar (0)




Ziyaretçi olarak yorum yazamazsınız. Üye olmak için tıklayın Üye iseniz giriş yapın.



MENÜ » FORUM
Menü » Takip et
RSS Facebook Twitter Friendfeed
Sık Kullanılanlar Google Yahoo Live
Menü » Paylaş
E-Posta ile gönder Twitter Facebook Friendfeed
Buzz Stumbleupon Delicious Digg