Free Essay

Java Outlines

In:

Submitted By mjeshtri
Words 4563
Pages 19
NJE VESHTRIM MBI JAVA JAVA eshte nje gjuhe programimi e orientuar ne objekte e cila eshte projektuar dhe zhvilluar nga ekipi i drejtuar nga James Gosling ne Sun Microsystems. Prezantohet zyrtarisht ne fund te vitit 1995. Ne ditet e sotme eshte nje nga gjuhet me te perdorura ne fushen e zhvillimit te software. Gjate projektimit te JAVA-s, qellimet kryesore ishin: Perdorimi i metodologjise se programimit te orientuar ne objekte. Te beje te mundur qe i njejti program te ekzekutohet ne sisteme operative te ndryshme. Te mbeshtese ne stilin “built-in” rrjetat kompjuterike. Te mundesoje ekzekutimin ne menyre te sigurt kodin nga kompjutera te ndodhur larg (secure remote execution ). Te mundesoje perdorimin e pjeseve nga gjuhe me te vjetra te programimit si C++ etj. Programet ne JAVA perbehen nga pjese te cilat quhen klasa (class). Klasat perbehen nga pjese qe quhen metoda (methods) te cilat kryejne detyra te caktuara dhe kthejne informacion kur i perfundojne ato. JAVA te jep mundesine te programosh çfaredo pjese qe mund te ju nevojitet kur ju formoni nje program. Gjithsesi te gjithe programuesit ne JAVA preferojne te mos e programojne gjithçka nga zeroja, por te shfrytezojne koleksionin e pasur te klasave ekzistuese ne Java Class Libraries (Bibliotekat e klasave te Javas), qe njihen gjeresisht si Java API’s (Application Programming Interfaces). Mund te themi qe programimi ne Java perbehet nga dy pjese te rendesishme: Programimi i klasave te projektuara nga vete programuesi. Perdorimi i klasave te bibliotekave te Java-s (API’s) (Keto dy pika nuk duhet te konceptohen si te veçuara por teresisht te nderthurura me njera-tjetren) Vini re: Perdorimi i klasave dhe metodave te Java API’s ne vend qe te shkruani versionin tuaj personal e rrit ndjeshem efiçiencen e programit sepse ato jane projektuar dhe programuar me kujdes nga profesioniste. Perveç kesaj, kjo permireson ndjeshem dhe kohen e nevojshme per realizimin e nje projekti.

BAZAT E NJE MJEDISI PUNE TIPIK NE JAVA Lista e nevojave paraprake 1. The JavaTM 2 Platform, Standard Edition duhet te jete i instaluar ne kompjuterin tuaj. (Mund te shkarkoni variantin me te fundit te tij nga faqja zyrtare e Sun Mirosystems http://java.sun.com ose te kontaktoni me instuktorin e kesaj lende qe te ju jape versionin e fundit qe i ndodhet)

1

2. Nje editues (redaktues) teksti. Mund te perdorni edhe NotePad, nga Start menu zgjidhni Programs > Accessories > NotePad, por te keshillueshem jane NotePad++, VIM etj Keto jane kerkesat paraprake baze per te programuar ne Java por shumica e programuesve preferojne te perdorin nje IDE (Integrated Development Environment) si psh Eclipse, NetBeans,Jcreator etj.

Hapat per krijimin e nje aplikacioni te tjeshte: 1. Krijoni skedarin e source code. Permban tekst te shkruar ne Java qe ju dhe programuesit e tjere mund ta kuptojne. Nuk ka fare rendesi cilin redaktues teksti perdorni per te krijuar dhe edituar (redaktuar) source code, perdorni ate me te cilin ndjeheni me mire. Kompiloni (perpiloni) skedarin e source code per te formuar skedarin qe permban bytecode. Kompiluesi ( javac) lexon skedarin e source code dhe e perkthen ne instruksione qe jane te kuptueshme nga Interpretuesi Java-s (JVM) Keshtu formohet nje skedar me zgjatimin *.class qe permban bytecode. Kompilimin mund ta kryeni nga Command Prompt me ane te komandes javac. Pra nje skedar source code te emertuar MyFirstApplication.java kompilhet me ane te komandes:
>javac MyFirstApplication.java

2.

3.

Ekzekutoni programin qe ndodhet ne skedarin e bytecode. Interpretuesi (JVM) e instaluar ne komjuterin ne cilin jeni duke punuar, lexon dhe ben te mundur ekzekutimin e tyre duke i perkthyer ne insruksione te kuptueshme nga komjuteri. Programi qe kompiluat me siper ekzekutohet nga Command Prompt me ane te komandes:
>java MyFirstApplication

2

VARIABLAT, OPERATORET, SHPREHJET Nje variabel tani per tani konsiderojeni si nje “kuti” ne memorje e cila perkohesisht mban nje informacion. Secila variabel ne nje program te caktuar duhet te kete nje emer te unik. Lloji i te dhenave (Data type) Çdo variabel duhet te kete nje lloj te dhene, gje e cila percakton vlerat qe variabli mund te marre dhe cilat operacione mund te kryhen me te. Ne Java ka dy kategori te llojeve te te dhenave: primitive dhe referenca. Me poshte jepet tabela e llojeve primitive te te dhenave: Keyword Integers Byte Short İnt Long Real numbers Float double Others Byte-length integer Short integer Integer Long integer Single-precision Double-precision 8-bit 16-bit 32-bit 64-bit 32-bit 64-bit 16-bit Description Size

char A single character boolean true or false (Per referencat do te flasim ne leksione te tjera)

Emri i variablit Per te emertuar variablat perdoren karaketere (‘a’ – ‘z’, ‘A’ - ‘Z’ dhe ‘_’ ) si dhe shifra ( 0 – 9) , por emri i nje variabli nuk mund te filloje me nje shifer , nuk mund te jete fjale kyce dhe nuk mund te kaloje nje limit te numrit te karaktereve (jo me shume se 256 karaktere)

Operatoret Aritmetike Binare: + (mbledhje), - (zbritje), * (shumezim), / (pjesetim), % (mbetje) Unare: ++(rrit nje njesi), -- (zbret nje njesi) Relacionale: == (te barabarte), != (te ndryshem), , =. Shenimi (assignment) : =, +=, -=, *= etj

3

NJE PROGRAM “Hello World” NE JAVA Ne programim, “Hello World” quhet nje aplikacion elementar qe (nuk perben asnje vlere ne boten reale dhe qe) printon ne ekran nje mesazh pershendetes. Programet “Hello World” sherbejne si nje mjet prezantues me elementet e gjuhes se programimit per fillestaret ne nje gjuhe te caktuar. Me poshte po japim nje program “Hello World” tipik ne JAVA:

/** * Klasa HelloWorldApp zbaton nje aplikacion te thjeshte * qe printon mesazhin "Hello World!" ne standard output (ekran). */ class HelloWorldApp { public static void main(String[] args) { System.out.println("Hello World!"); //Shfaq mesazhin. } }

Ne fig jepet permbajtja e skedarit HelloWorldApp.java Siç u permend ne leksionin e kaluar, kete aplikacion mund ta kompiloni nga ekrani i Console me ane te komandes: >javac HelloWorldApp.java dhe me pas ta ekzekutoni HelloWorldApp.java me me ane te komandes: >java HelloWorldApp Tashme le te shikojme disa nga elementet perberes te JAVA-s duke i konkretizuar ne kodin e mesiperm: Komentet: jane pjese te kodit te cilat nuk merren ne konsiderate nga ana e kompiluesit (perpiluesit) dhe qe sherbejne thjesht per te rritur lexueshmerine e kodit dhe per dokumentime. Per kompiluesin nuk ka asnje ndryshim nese i fshijme te gjithe komentet ne nje program te caktuar. Ne Java ka dy lloje komentesh: /* text */ Kompiluesi nuk merr parasysh gjithçka qe ndodhet midis /* dhe */. // text Kompiluesi nuk merr parasysh gjithçka nga // deri ne fundin e rreshtit. (Nqs komenti fillon me /**, serish perfshihet ne llojin e pare te komenteve nga ana e kompiluesit, por kemi te bejme me nje koment dokumentimi qe njihet dhe proçedohet nga nje mjete te tjera si javadoc )
/** * Klasa HelloWorldApp zbaton nje aplikacion te thjeshte * qe printon mesazhin "Hello World!" ne standard output (ekran). */ class HelloWorldApp { public static void main(String[] args) { System.out.println("Hello World!"); //Shfaq mesazhin. } }

Komentet ne HelloWorldApp.java 4

Definicioni i klasave: Ne Java çdo metode (funksion) dhe variabel ekziston brenda nje klase ose objekti (instance te nje klase). Java nuk mbeshtet parimin e funksioneve dhe variablave globale. Pra, skeleti i çdo programi ne Java eshte definicioni i nje klase.

/** * Klasa HelloWorldApp zbaton nje aplikacion te thjeshte * qe printon mesazhin "Hello World!" ne standard output (ekran). */ class HelloWorldApp { public static void main(String[] args) { System.out.println("Hello World!"); //Shfaq mesazhin. } }

Blloku i definicionit te klases HelloWorldApp Pra, forma me e thjeshte e definicionit te nje klase ne Java eshte: class {
. . . }

Metoda main: Pika e fillimit te ekzekutimit te çdo programi ne Java eshte metoda main. Per te ekzekutuar nje aplikacion me ane te interpretuesit JVM, ju specifikoni emrin e klases qe doni te ekzekutoni. Interpretuesi (JVM) therret metoden main qe eshte e deklaruar ne klasen ne fjale. Metoda main kontrollon rrjedhen e programit, percakton rezervat qe do te perdoren dhe therret metodat e tjera qe mundesojne funksionalitetin e programit.

/** * Klasa HelloWorldApp zbaton nje aplikacion te thjeshte * qe printon mesazhin "Hello World!" ne standard output (ekran). */ class HelloWorldApp { public static void main(String[] args) { System.out.println("Hello World!"); //Shfaq mesazhin. } }

Metoda main ne klasen HelloWorldApp

5

STRUKTURAT IF dhe IF/ELSE Ne programim, ne skenare te caktuara, ekzistojne blloqe qe doni t’i ekzekutoni ne menyre selektive ne baze te disa kritereve. Zgjidhja ne kete rast eshte perdorimi i strukturave te kontrollit “if” ose “if-else”. Variablat boolean Ne boten e programimit, ndryshe nga bota reale, çdo gje eshte ose e sakte ose e gabuar, ose e vertete ose e rreme, nuk behet fjale per saktesi apo vertetesi te pjesshme. Psh nqs keni krijuar nje variabel x te llojit integer, te ciles i keni dhene vleren 99, dhe me pas shtrohet pyetja “A eshte x ibarabarte me 99 ?”, pergjigjja do te jete “po (e vertete)” ne menyre strikte. Po keshtu nese do te shtrohej pyetja “A eshte x me i vogel se 32 ?” pergjigjja do te ishte “Jo, (e rreme)” ne menyre strikte. Keto qe sapo permendem jane shembuj shprehjesh boolean (shprehje vlera e te cilave eshte ne menyre strikte ose e vertete ose e rreme, true/false). Siç kemi permendur me pare, Java permban nje lloj primitiv variabli te emertuar boolean i cili mban vlerat logjike, pra nje nga dy vlerat e vertete/e rreme (true/false). Po japim disa shembuj me deklarime variablash int dhe boolean: int x = 7, y = 10, z = 15; boolean b1, b2, b3, b4; b1 = ( x >= y ); b2 = ( x + z > y ); b3 = ( x < y ) && ( x < z); b4 = ! b3

//false //true //true //false

Perdorimi i “if” “if” perbehet nga dy pjese: 1. kushti dhe 2. bashkesia e veprimeve qe kryhen nqs kushti eshte i vertete: if ( ) { < instruksionet> } Supozojme se jemi duke programuar ne nje skenar te tille qe nese vlera e variablit totali te llojit integer, e kalon 100 duhet te njofojme me nje mesazh ne ekran: if (total > 100) { System.out.println( “Totali kaloi vleren 100”); }

Perdorimi i “if-else” Po ne qofte se do te donit te kryenit nje bashkesi tjeter veprimesh nese kushti brenda “if” eshte i rreme? Pergjigjja eshte perdorimi i “if-else”. Supozojme se jemi duke programuar klasen Kronometer :

6

public class Kronometer { int sekonda = 0; int minuta = 0; public void shtoSekonde() if( sekonda == 59 ){ sekonda = 0; mınuta ++; }else{ sekonda++ } } } { // nese numri i sekondave eshte 59 // sekondave u japim vleren 0 //rrisim minutat nje njesi //perndryshe rrisim sekondat nje njesi

Perdorimi i “if-else if” te shkallezuar. Supozojme se jemi duke programuar ne nje skenar ku ne varesi te pikeve qe nxenesi ka marre ne provim, do te percaktojme noten qe ai meriton. Perdorimi i “if-else” te shkallezuar konkretizohet mjaft qarte me kete shembull:
... if ( piket >= 90) { nota = ‘A’; } else if ( piket >= 80) { nota = ‘B’; } else if ( piket >= 70) { nota = ‘C’; } else if ( piket >= 60) { nota = ‘D’; } else { nota = ‘F’; } System.out.println(“Nxenesi mori noten “ + nota);

...

7

CIKLET Pame se me ane te strukturave “if” dhe “if-else”, nje bashkesi veprimesh ekzekutohej te shumten nje here (pra 0 ose 1 here) ne varesi te nje ose disa kritereve. Po sikur nje bashkesi veprimesh, te donim te perseritej me shume se nje here? Ne kete rast pergjigjja do te ishte perdorimi i cikleve. Ne Java ka tri lloje ciklesh while, for dhe dowhile. Cikli while. Eshte modeli me i thjeshte i nje cikli. Bashkesia e veprimeve qe ndodhen ne bllokun e ciklit, perseriten sa kohe qe kushti i ciklit eshte i vertete. Struktura e pergjithshme e ketij cikli eshte: while ( < kushti > ) { < instruksionet> } Po e konkretizojme me nje pjese kodi qe shkruan ne ekran numrat nga 1 ne 10: ... int i = 1;

while ( i ; < rifreskimi i variablit te kontrollit > ) { < bashkesia e veprimeve > } Po e konkretizojme me te njejtin shembull si me siper: ... for ( int i = 0; i < 10; i++ ){ System.out.println( i ); } ...

8

Cikli do-while Ngjan shume me ciklin while, ndryshimi i vetem eshte se blloku i ciklit do-while ekzekutohet te pakten nje here pavaresisht nese kushti eshte i vertete apo i rreme. E konkretizojme serish me te njejtin shembull: ... int i = 0;

do{ System.out.println( i ); i++; }while ( i < 10 ); ...

Studim rasti: Vargu Fibonaçi. Eshte i njohur ne matematike vargu 1, 1, 2, 3, 5, 8, 13, ... ku çdo term eshte i barabarte me shumen e dy termave paraardhes. Po paraqesim nje program qe llogarit dhe printon ne ekran nr e 100 te ketij vargu. Analizojeni, ekzekutojeni ne laborator. Mund te gjeni vlerat edhe te termave te tjere te vargut (jo vetem te termit te 100-te) duke ndryshuar vleren fillestare te variablit radha. public class public int int int int int TermiFibonaci { static void main(String[] args ){ termiParafundit= 1; termiFundit=1; numeruesi = 2 ; radha = 100; mbajtes;

while( numeruesi < radha ){ mbajtes = termiParafundit; termiParafundit = termiFundit; termiFundit = mbajtes + termiFundit; numeruesi ++; } System.out.println( “Termi i ” + radha + “ eshte ”+ termiFundit); } }

9

METODAT Programet qe zgjidhin probleme te botes reale jane shume me te medhenj se programet elementare me te cilet jemi prezantuar deri tani. Jo vetem kaq, ato ne shumicen e rasteve jane teper te medhenj per t’u programuar nga nje programues i vetem sado me eksperience te jete ai. Eksperienca ka treguar se menyra me mire per te ndertuar nje program te madh eshte ta formosh ate nga pjese te vogla te thjeshta, te quajtura module. Kjo teknike njihet si “divide and conquer” (e pershtatur ne shqip: “perçaj dhe sundo”). Kemi permendur edhe me pare se modulet ne Java jane klasat dhe metodat. Programet ne Java ndertohen si kombinim i klasave dhe metodave te vete programuesit si dhe klasave dhe metova te “paketuara” ne Java API (te ashtuquajtur Biblioteka e Klasave te Javas) Ne kete leksion do te perqendrohemi teresisht mbi metodat. Klasat do te kemi mundesi t’i diskutojme ne leksionet e ardhshme.

Formati i pergjithshem i prezantimit te nje metode eshte: (lista e parametrave){ .... return ; // sentenca mbyllese } Konkretisht nje metode (shume e thjeshte) qe kryen mbledhjen e dy numrave te plote (integer) do te ishte:

Ne figure jepen: 1 – lloji i vleres qe kthehet 2 – emri i metodes 3 – lista e parametrave

Lloji i vleres qe kthehet ( return type ) Kemi permendur qe “ ...metodat kyejne detyra te caktuara dhe kthejene informacion ne perfundim te tyre...” (leksioni nr2, fq1). Pikerisht “return type” percakton se i cilit lloj do te jete informacioni qe metodat kthejne ne perfundim te detyres. Vlerat qe kthjene metodat mund te jene nje nga tri llojet e meposhtmpe: lloj primitiv (int, short, long, double, float, char, boolean etj) reference void, ky nuk eshte ndonje lloj i ri, por eshte thjesht fjala çeles qe qe shkruhet per te bere te ditur se metoda nuk kthen asgje (kryen nje detyre te caktuar dhe nuk kthen asnje informacion ne perfundim te saj) Emri i metodes Konvencionet e emertimit te metodave jane te njeta me ato te variablave: perbehen nga karaktere ‘a’-‘z’ dhe ‘A’-‘Z’, si dhe nga shifra 0-9, me kusht qe emri te mos filloje me nje shifer.

10

Lista e parametrave Eshte e formatit ( parametri1, parametri2, ..., parametrin) ose, nese metoda nuk merr asnje parameter thjesht shkruhen dy kllapat () dhe lihen bosh. Vini re qe parametrat jane te ndare me presje nga njeri – tjetri. Thirrja e metodave Metodat ‘aktivizohen’ kur ato thirren. Thirrja e nje metode eshte shkrimi ne nje sentence i emrit te saj dhe kalimi i argumenteve. Argumentet e kaluara perputhen rigorozisht ne numer, lloj dhe radhe me parametrat ne definicionin e metodes. Per llojet primitive, argumentet kalohen si vlera inputi per metoden dhe ajo proçeson ne baze te tyre. Me poshte do te shikojme nje kod te plote (me kod te plote nenkuptoj nje kod qe mund ta kompiloni dhe ekzekutoni siç eshte, pa i bere plotesime) ku ndodhet nje metode qe merr si parametra dy numra te plote dhe nje karakter, dhe kryen nje veprim aritmetik ne baze te llojit te karakterit ‘+’, ‘-’, ‘*’, ‘/’, i cili perfaqeson llojin e operatorit aritmetik. Vini re argumentet qe kemi kaluar ne sentencen c = veprimAritmetik( a , b, ‘+‘ ); perputhen ne numer, lloj dhe radhe me parametrat ne definicionin e metodes: public static int veprimAritmetik( int nr1, int nr2, char op) Gjithashtu lloji i variabilit c, ne te cilin kemi bere hedhjen e vleres se kthyer nga thirrja e metodes, perputhet me “return type” (llojin e vleres qe kthehet) te metodes (qe te dy jane te llojit “int” ) .

public class PakAritmetike{ public static int veprimAritmetik( int nr1, int nr2, char op){ int rezultati; if( op == ‘+’){ rezultati = nr1 + nr2; }else if(op == ‘-’){ rezultati = nr1 - nr2; }else if(op == ‘*’){ rezultati = nr1 * nr2; }else if(op == ‘/’){ rezultati = nr1 / nr2; } return rezultati; } public static void main(String[] args){ int a = 6, b = 2; int c , d; c = veprimAritmetik( a , b, ‘+‘); //thirrje e metodes d = veprimAritmetik( 14 , b, ‘/’); //thirrje e metodes System.out.println( " a = " + a + "b = " + b + "c = " + c + "d = " + d); } }

11

Rrjedha e programit ndermjet moduleve (flow between subprograms) Siç permendem, nje program kur ekzekutohet (me ane te komandes > java ), interpreteri therret metoden main te klases ne fjale. Pra metoda main eshte pika e fillimit te ekzekutimit te çdo programi. Po si vazhdon rrjedha me tej? Sentencat dhe deklarimet qe ndodhen ne metoden main fillojne te ekzekutohen me radhe. Ne momentin qe thirret nje metode, kontrolli i rrjedhes kalon totalisht ne dore te metodes dhe kur metoda ka mbaruar, kontrolli kthehet pikerisht ne piken ku metoda eshte thirrur. Nderkohe e rendesishme eshte te dihet se nje metode mund te therrase nje metode tjeter; ne kete rast kontrolli i rrjedhes do t’i kaloje metodes se therritur dhe ne momentin qe ajo mbaron, kontrolli kthehet pikerisht ne piken ku metoda eshte thirrur. Pra, e gjithe kjo realizohet ne stilin ‘stack’ ( per jo pjesemarresit ne leksion eshte detyre te gjejne informacion rreth ‘stack’ dhe te jene te afte ta konkretizojne ne rrjedhen e kontrollit ) Me poshte jepet nje kod i plote, funksionaliteti i te cilit eshte shume i lehte per t’u kuptuar. Analizojeni, ekzekutojeni, eksperimentoni !! Vini re ne programin e meposhtem si rrjedha e programit kalon : main → shkruajNoten → gjejNoten → shkruajNoten → main → shkruajNoten → gjejNoten → shkruajNoten → main ...etj public class ProvojmeMetodat{ public static char gjejNoten( char nota; if ( piket >= 90) { nota = ‘A’; } else if ( piket >= 80) nota = ‘B’; } else if ( piket >= 70) nota = ‘C’; } else if ( piket >= 60) nota = ‘D’; } else { nota = ‘F’; } return nota; } int piket ){

{ { {

public static void shkruajNoten(String emri,String mbiemri,int piket){ char nota = gjejNoten(piket); System.out.println("Nexenesi " + emri + " " + mbiemri + "mori noten" + nota + "." ); }

public static void main(String[] args ){ shkruajNoten("Steve","Jobs", 85 ); shkruajNoten("Mark", "Zuckerberg", 71 ); shkruajNoten("Bjarne","Stroustrup”, 80 ); shkruajNoten("Donald", "Knuth", 100 ); shkruajNoten("Andrew", "Tanenbaum", 77 ); shkruajNoten("Linus","Torvalds", 95 ); } }

12

VEKTORET (ARRAYS) Ne kete leksion do te kemi mundesine te prezantohemi me nje teme shume te rendesishme te strukturave te te dhenave: vektoret (arrays). Keto jane struktura qe permbajne nje liste elementesh te te njetit lloj. Vektoret jane elemente statike, dmth kane nje madhesi te caktuar te pandryshueshme. (Ne leksione te mevonshme do te kemi mundesi te prezantohemi dhe me elemente dinamike, permasat e te cileve rriten apo zvogelohen gjate ekzekutimit te programit.) Nje vektor (array) eshte nje grup qelizash fqinje ne memorje qe mbajne vlera te te njejtit loj. Per te referuar nje qelize specifike ne nje vektor, ne thjesht specifikojme emrin e vektorit dhe numrin e pozicionit (indeksin) te kesaj qelize te futur brenda kllapave katrore [ ]. Ne figuren e meposhtme tregohet nje vektor me nr te plote (integer), i quajtur c, i cili permban tete elemente. Nje program mund te referoje secilin nga keto elemente duke dhene emrin e vektorit te ndjekur nga indeksi i elementit i futur brenda kllapave katrore. - 45 c[0] 6 c[1] 0 c[2] 178 c[3] -5 c[4] 21 c[5] 1 c[6] - 14 c[7]

Pas nje sentence si c[2] = 15; pamja e vektorit do te ishte: - 45 c[0] 6 c[1] 15 c[2] 178 c[3] -5 c[4] 21 c[5] 1 c[6] - 14 c[7]

Pas nje sentence si c[5] = 4*c[1] - c[0]; pamja e vektorit do te ishte :

- 45 c[0]

6 c[1]

0 c[2]

178 c[3]

-5 c[4]

69 c[5]

1 c[6]

- 14 c[7]

Supozojme se po programojme ne nje skenar te tille ku kemi shtate nxenes dhe do te mbajme neper variabla notat e tyre. Nqs ne nuk do te kishim njohuri rreth vektoreve, zgjidhja qe do te na vinte ne mendje do te ishte deklarimi i shtate variablave te llojit char (supozojme notat i kemi ne sistemin A, B, C ...) si me poshte dhe mund te hidhnim vlera mbi to si vijon: char notaNx0, notaNx1, notaNx2, notaNx3, notaNx4, notaNx5, notaNx6; notaNx0 = ‘B’; notaNx1 = ‘A’ notaNx2 = ‘D’; notaNx3 = ‘F’ ; //etj

Ne rast se do te punonim me vektore, gjithçka do te ishte me lehte: char notat[] = new char[7]; notat[0] = ‘B’; notat[1] = ‘A’ notat[2] = ‘D’; notat[3] = ‘F’ ; //etj //vektori qe do te mbaje notat

13

Imagjinojeni dhe nje here skenarin e mesiperm, por kete here nr i studenteve te mos jete 7, por 70. Nqs do te punonim me stilin e pare, pra te prezantonim 70 variable me radhe, do te na kalonte dita vetem duke u marre me kete pune. Kurse duke punuar me vektore nuk do te komplikohej asgje: char notat[] = new char[70]; //vekt. e notave e percaktojme me 70 elemente notat[45] = ‘C’; //nxenesi i 45-te mori noten C ... notat[31] = ‘A’ // nxenesi i 31-te mori noten A ... etj notat[66] = ‘B’; notat[3] = ‘F’ ;

Deklarimi dhe percaktimi i permases se vektoreve Me siper pame si deklarohej dhe si percaktohej permasa e nje vektori. Ngjashmeria me deklarimin e variablave primitve eshte shume e madhe. Ndryshimi i rendesishem eshte se nje variabel primitiv eshte i gatshem te perdoret menjehere pas deklarimit, kurse ne rastin e nje vektori ka nevoje dhe per diçka tjeter: percaktimin e permases. Percatimi i permases mund te behet ne te njejtin rresht (sentence) me deklarimin siç e kemi bere me siper ose ne dy sentenca te ndryshme siç eshte bere me poshte. (Nuk ka ndonje ndryshim midis dy rasteve, eshte njesoj si te besh nje deklarim dhe inicializim te nje variabli integer me nje sentence si psh int x = 5; ose te besh ne fillim deklarimin int x; dhe pastaj hedhjen e vleres x = 5;). int njeNumer; int disaNumra[]; //deklarimi i nje variabli integer //deklarimi i nje vektori me nr te plote (int)

disaNumra = new int[20]; //percaktimi i permases se vektorit njeNumer = 67; disaNumra[5] = 39; //variabli primitiv perdoret direkt pas deklarimit //vektori perdoret pas dekl. dhe percak. permases

Ekziston dhe nje menyre tjeter me “direkte” per deklarimin dhe percaktimin e permases se nje vektori: perdorimi i nje liste inicializuese. int n[] = { 8, 25, 17, 265, 101 }; //deklarimi dhe perc. permases //me ane te nje liste inicializuese

Kjo eshte totalisht e njevlershme me: int n[] = new int[5]; //deklarimi dhe percaktimi i permases n[0] = 8; n[1] = 25; n[2] = 17; n[3] = 265; n[4] = 101;

Eshte e qarte qe rasti i pare eshte shume me praktik, vetem se ai vlen vetem kur e dime cilat vlera fillestare do te kete nje vektor, gje e cila nuk ndodh shpesh ne programim.

14

Studime rastesh: Gjetja e shumes se elementeve te nje vektori. public class ProvojmeVektoret{ public static void main(String[] args ){ int numra[] = { 15, 17, - 81, 55, 211, - 54, 79 }; int shuma = 0; for( int indeks = 0; indeks < 7; indeks++ ){ shuma = shuma + numra[indeks]; } System.out.println(“Shuma e elementeve te vektorit eshte” + shuma); } }

Gjetja e elementit minimal dhe maksimal ne nje vektor: public class ProvojmeVektoret{ private static double temperaturat = { 22.5, 17.2, 28.8, 12.1, 5.7, 11.4, 19.6, 22.7 }; public static double temperaturaMinimale(){ int tempMin = temperaturat[0]; //supozojme me i vogli é elementi i pare for( int indeks=0; indeks < 8; indeks++ ){ if( temperaturat[indeks] < tempMin ){ tempMin = temperaturat[indeks]; } } return tempMin; } public static double temperaturaMaksimale(){ int tempMax = temperaturat[0]; //supozojme me i madhi é elementi i pare for( int indeks=0; indeks < 8; indeks++ ){ if( temperaturat[indeks] > tempMax ){ tempMax = temperaturat[indeks]; } } return tempMax; } public static void main(String[] args ){ System.out.println(“Temp. minimale eshte ” + temperaturaMinimale() ); System.out.println(“Temp. maksimale eshte ” + temperaturaMaksimale() ); } }

15

PROGRAMIMI I ORIENTUAR NE OBJEKTE Deri tani kemi folur rreth klasave, rreth metodave, variablave te instancave, variablave statike etj. Kemi permendur gjithashtu se klasat jane shabllone qe pershkruajne atributet (veçorite) dhe sjelljen e instancave (objekteve) te tyre. Nje objekt eshte nje instance e nje klase, i cili ka te njejten kategori te dhenash dhe te njejten kategori sjellje me instancat e tjera te klases ne fjale. Gjithashtu kemi permendur qe kemi variablat primitive dhe referencat. Pra, vazhdimisht kemi folur ne menyre indirekte rreth objekteve dhe tani (me ne fund) do te kemi mundesine te flasim ne menyre direkte rreth objekteve. Do te marrim si shembull konkretizues klasen Koha ku kemi prezantuar disa variabla instancash: public class Koha{ int ora; int minutat; int sekondat; ... }

Fillojme me nje paralelizem ndermjet tri deklarimeve: double x; long y[]; Koha z; //nje variabel primitiv i llojit double // nje array me variabla te llojit long //nje refenrece e nje objekti te llojit (klases) Koha

Eshte e qarte se variabli x, duke qene nje variabel primitiv, eshte i gatshem te perdoret menjehere. Pra, ne momentin qe ne bejme deklarimin, marrim nje qelize ne memorje e cila ka madhesi caktuar (64 bit/ 8byte) e cila eshte e rezervuar per te mbajtur variabla te llojit double (double precision/ nr me presje). Kurse ne rastin e daklarimit te nje vektori (array) ose te nje reference objekti, serish marrim nje qelize ne memorje, por ajo eshte nje qelize qe mban nje vlere adrese (vlere refencuese) dhe sa kohe qe nuk eshte bere rezervimi i memorjes, ajo eshte e paperdorshme. Per rastin e nje (array), tashme e dime se rezervimi i memorjes (percaktimi i pemases) behet me ane te nje sentence te tille si y = new long[8]; Kjo sentence rezervon ne memorje nje array prej 8 variablash long. Tashme le te kalojme ne rastin e objektit. Ekziston ngjashmeria me rastin e rezervimit te memorjes vetem se ne kete rast nuk rezervohet vend per nje grup qelizash identike, por memorja e rezervuar ndryshon ne varesi te llojit te variablave te instancave. y

y[0]

y[1]

y[2]

y[3]

y[4]

y[5]

y[6]

y[7]

Kurse per nje reference objekti si psh Koha, rezervimi i memorjes do te shenonte ne qelizen z, adresen e nje strukture si figuren me poshte:

16

z

...

Tashme arritem ne piken kyçe: cila eshte menyra me ane te te ciles ne do te kryejme rezervimin e memorjes per referencat e objekteve?

KONSTRUKTORET (CONSTRUCTORS) Konstruktoret jane metoda te veçanta te cilat mundesojne krijimin e objekteve te nje klase te caktuar. Me poshte po japim disa nga vetite e konstruktoreve: Konstruktoret nuk kane lloj te vleres qe kthehet (no return type). Konstrktoret marrin nje liste parametrash njesoj si nje metode e zakonshme. Konstruktoret kane te njejtin emer me emrin e klases. Nje klase mund te kete disa konstruktore, te cilet dallojne nga lista e parametrave qe ata marrin. Le te vazhdojme me shembullin qe patem nisur: public class public int public int public int Koha{ ora; minutat; sekondat;

/* Nje konstruktor qe nuk merr asnje parameter, * sherben per te krjuar nje objekt kohe fillestare */ public Koha(){ ora = 0; minutat = 0; sekondat = 0; } /* Nje konstruktor qe merr si parametra oren or dhe mintat m, * dhe krijon me ato nje objekt kohe ,, */ public Koha( int or, int m ){ if ( or >= 0 && or =0 && minutat =0 && sekondat = 0 && or =0 && minutat =0 && sekondat = 0 && or = 0 && min = 0 && sek

Similar Documents

Free Essay

I Dont Know

...My overall impression on my speech was better than I anticipated. I was very nervous and anxious to get the speech over. I could tell that in the pace of my speech. I was rushing through it and at times it was hard for me to keep track of my place on the outline. I thought I gave good eye contact and I stayed on the speech path, but I could have projected my voice more so that it would have been easier to hear and understand what I was saying. I felt that the delivery was good but I could have moved around more and gave more hand gestures to keep my speech alive. Although I didn’t feel it was a boring speech, I feel like I still tell showed how nervous I really was by the body chemistry I gave off. I prepared a lot for the speech and I went over the speech 3 times in front of the camera at home. I think this helped me a great deal because I had full knowledge of what my speech was about. Because I was nervous and rushing through my speech I often lost my place on my outline, but was able to wing it because I had practiced. It helped a lot that I did my speech on a topic that I am very familiar with and used to talking about. I also used the technique in the chapter that tells you that when you are nervous take a deep breath and use a focus word, mine was “Money”. This technique helped me a great deal in the beginning because I actually felt overwhelmed and on the verge of an anxiety attack. Using this technique calmed me down and made me able to deliver my speech. ...

Words: 476 - Pages: 2

Free Essay

Paper

...Research or Interview Paper Instructions You can choose 1 of the following two options for your Research or Interview Paper. Your paper will be 7 double-spaced pages for the main content (not including the cover page and reference page). Your choices include: 1. A research paper Steps for writing the research paper: a) Choose a topic in Managerial Economics. b) Submit the topic and the outline of the paper to the instructor anytime for approval. c) A minimum of 3 references besides the textbook are required. Liberty University library has excellent resources for your search for journals. http://www.liberty.edu/index.cfm?PID=178 OR 2. An interview paper Steps for writing the interview paper: a) Choose a topic in Managerial Economics. b) Design at least 5 questions according to the topic. c) Submit your questions to the instructor for approval. d) Contact a local or non-local company for an interview. e) Conduct the interview for answers to your questions. f) The paper must have 3 parts: • The description of the company; • Interview questions and answers; and • Your comments. *The research paper is to be done individually, not as a group. **Do not wait until the last module/week to work on the paper. Do it as early as possible. ***A paper that was written for other classes would not be accepted for...

Words: 265 - Pages: 2

Free Essay

Week 9 Iw Assignment Worksheet

...Composition I Week 9 IW Assignment Worksheet Instructions: As you did in Week 3, please fill in the answers to the prompts on this worksheet and save them as a Word doc. You are only filling in the blue areas! Then, attach your completed worksheet to your drop box submission. You will work to create your thesis statement and a basic outline for a comparison/contrast essay. There are two patterns from which to choose, and you will select ONE below. Creating a Thesis Statement and Basic Outline for the Comparison/Contrast Essay I.) First, you’ll choose two items to compare and contrast. There are some great examples of items to compare/contrast on pages 229-230 in our textbook, especially #9, #10, #11, #12, #14, and #15. Fill in the two items that you will compare/contrast. A.) Nokia 7110 – the first effort at taking the Internet onto a mobile (1999) B.) Amazon Fly – Taking Image Recognition Software to its next level (2014) II.) Next, you will identify three criteria that you’ll use to evaluate each of the items. Think about three qualities or characteristics of the two items that you can evaluate to choose the better item. For example, in the Week 10 Sample essay, the writer compares/contrasts the cost, nutrition and taste of two types of bread. Fill in the three evaluative criteria you will use to decide which of your two selected items is better. 1.) Internet capability 2.) Ability to take pictures and record videos 3.) Text messaging III.)...

Words: 631 - Pages: 3

Free Essay

Procedure for Writing a Term Paper

...PROCEDURE FOR WRITING A TERM PAPE A term (or research) paper is primarily a record of intelligent reading in several sources on a particular subject. The task of writing such is not as formidable as it seems if it is thought out in advance as a definite procedure with systematic perpetration. The procedure for writing such a report consists of the following steps: 1. Choosing a subject 2. Finding sources of materials 3. Gathering the notes 4. Outlining the paper 5. Writing the first draft 6. Editing the paper Now let's look at each of them. CHOOSING A SUBJECT Most good papers are built around questions. You can find subjects in any textbook. Simply take some part of the text that interest you and examine it carefully. Ask yourself the following things about it to see if you can locate a question to answer in your paper. Does it tell you all you might wish to learn about the subject? Are you sure it is accurate? Does the author make any assumptions that need examining? Can two of the more interesting sections in the text be shown to be interrelated in some useful way? Your paper is an attempt to write a well-organized answer to whatever question you decide upon, using facts for the purpose of proving (or at least supporting) your contention. The most common error made by students in choosing a subject for a term paper is to choose one that is too general. (The most specific subject will always have enough aspects to furnish a long paper, if you think...

Words: 1279 - Pages: 6

Free Essay

Classroom Tab

...the page next to the home tab. Click the classroom tab. The student’s next page will be the current class the student is participating in. Under the classroom tab are four new tabs. They are materials, discussions, assignments, and grades. The University of Phoenix is geared for adult learners. UoP has a very extensive user friendly website for the active learner. Figure 1.3 CLASSROOM TAB 5.1.1 COURSE OUTLINE When the student has clicked the classroom tab, the next screen will be automatically being the materials tab. The tabs are located at the top of the screen, directly under the classroom tab. In the materials tab the student will have a variety of information at their fingertips. Located on the left will be the course outline. The outline will give the student an overview of week to week activities. It will also give the student a course overview, and course policies. The student has the ability to access an overview of the course. Figure 1.4 MATERIALS TAB, COURSE OUTLINE 5.1.2 POLICIES Under the course outline there is a link for policies. When the link is clicked on, it will open another window. It will give the student the opportunity to read all the policies and procedures of UofP. It gives the user the opportunity to read all the rules and policies under several different types of students. 5.2 DISCUSSION TAB Next to the materials tab at the top of the page is the discussion tab. Under the discussion tab are the forums...

Words: 597 - Pages: 3

Premium Essay

Introductory Presentation

...Introductory Presentation ------------------------------------------------- ------------------------------------------------- Purpose of Presentation: to introduce yourself as a (potential) professional ------------------------------------------------- Audience: class members and your tutor ------------------------------------------------- Due: Week 3 Seminar 1 (Week starting 27 August 2012) ------------------------------------------------- Time limit: (3 minutes, Powerpoint not required) ------------------------------------------------- This presentation is video-taped. ------------------------------------------------- Short written outline of your presentation (one page or less), submitted to your tutor ------------------------------------------------- in hard copy on the day you present. ------------------------------------------------- Presentation Assignment Prepare a presentation to introduce yourself to your class and tutor. The speech will be videotaped for your review and self-assessment. Your presentation should be thoroughly planned, outlined, and rehearsed but not memorized or read. This handout covers the introductory presentation assignment, procedures for giving most business presentations, and a specific assessment sheet to help you prepare your talk and to give peer feedback. TASK: Adapt to Audience and Purpose Prepare and rehearse a presentation to develop your professional identity, establish rapport with your peers, and practise...

Words: 2525 - Pages: 11

Free Essay

Places to Go for Business and Managment

...topic: Security Issues involved with the transition from IPv4 to IPv6-Goal for next week: have all of our research papers together to divide among the team Team Meeting #2 10/2/2013 -All team members were present -Shared research papers among the team. Discussed potential topics for next semester to get a better idea of what to include in this phase of the paper. Team Meeting #3 10/9/2013 -All team members were present. - Discussed important points to cover based on our research, and laid down a rough outline for the background and introduction. Created and shared Google docs for the outline and for collaborative list of citable resources. Goal for this week: continue research and begin filling in the outline. Team Meeting #4 10/16/2013 -All team members were present -Continued filling in the outline. -Goal for next week: Have it mostly complete! Team Meeting #5 10/23/2013 -All team members were present -Busy week for everyone. Continued filling in the outline. Team Meeting #6 10/30/2013 -All team members present. -Continued filling in rough draft. Working on continuity. Team Meeting #7 11/6/2013 -All team members were present -Mostly done with rough draft. Working to add more technical info into body. Team Meeting #8 11/13/2013 -All team members were present -Not much progress this week. Team focused on project 2. Team Meeting #9 11/20/2013 -All team members were present -Not much progress this week. Team focused on project 2. Team Meeting...

Words: 282 - Pages: 2

Free Essay

Demonstrative Communication

...websites, before choosing one that I deemed credible. Aaron started the outline, and we all agreed to turn in our assigned sections of the outline. However, Michael informed us he would not be attending class, so we had to complete his section. We decided to post our portions of the presentation to OLS. On Monday I posted all of my information, and added all information and the outline. Aaron added the conclusion and posted all of the work between the both of us. We put the information together even though our third person quit. I think our presentation would have been better if we would have known sooner that Michael would not be a part of the project. Aaron and I didn’t have the opportunity to meet and go over our presentation together. Aaron works nights, making it hard for him to meet during the day. Alternatively, we decided to post our work to OLS, in order to modify our work together. I posted all of my slides on Sunday night, and Aaron reviewed them. He also added pictures and created the quiz, and then added some pictures to the slide. After, I looked over our work and increased the amount of questions we had for the quiz, along with additional pictures for the slides. Aaron looked it over one last time, then proceeded to post our outline and PowerPoint. The ouline was not very difficult to create, as we just restructured the information on our slides into a condensed format better suited for an outline. The presentation was started by Aaron, who took longer than expected...

Words: 364 - Pages: 2

Free Essay

Jerks

...successfully perform a step in the speech, show me how you would correct the problem I noted on your evaluation form. Your Name: Section # Persuasive Speech Questions 20 pts. *1. Write the outline for the introduction of your speech. Provide a complete specific purpose and overview of main points. Also present a complete bibliography of the sources you used. Provide brief summaries of the other two steps. Outline for Introduction Step 1- Step 2- Step 3- Step 4- Step 5- 20 pts. *2. Write the outline for the body of your speech. Provide complete transitions in between each main point. Provide paragraph summaries for each main point. Outline for Body Main Point #1 Main Point #2 Main Point #3 Main Point #4 10 pts. *3. Write the outline for the conclusion of your speech. Provide a complete restatement of main points and specific purpose. Provide brief summaries of the other two steps. Outline for Conclusion Step 1 Step 2 Step 3 Step 4 *Do not write out the entire speech. The only steps in the three (3) parts of the speech that I want written out completely are noted in the question (e.g. transitions in the body.) As noted, only summaries of all other steps should be provided. *Answers to questions 1, 2 and 3 must be in outline form or you will receive 0 points for your answer. 25 pts. 4. Provide four examples of how you adapted your persuasive speech...

Words: 401 - Pages: 2

Free Essay

1122121

...anything. Any fanciful cover that you would like to enclose should be placed after the Assignment Front Cover. Copies of the Assignment Front Cover are available at the information counter at the respective College in which you are studying. Kindly ensure that all details requested for on the front cover are completed and that the recipient of your assignment counter signs, acknowledging receipt. Remember to keep a copy of the assignment cover sheet as proof of submission. |[Type College Name] | [Type Subject Name] Executive Summary [Type short paragraph on the outline of assignment which is relevant to the assignment being presented] Student Particulars |Name | | | |IC Number | | | |Student Number | | | |Course | | | |Subject Title | | | |Subject Code ...

Words: 252 - Pages: 2

Free Essay

Arjun

...material to work with, start outlining your speech. Use brief sentences to write out an introduction, a thesis, two main points, and a conclusion. Your thesis (and therefore, your speech) should address the following question: what kind of person is my classmate? Think about two qualities or attributes that describe your partner. Your classmate could be someone like: a sports fan, a musical talent, an outdoorsman, a car enthusiast, a spontaneous free spirit, or anything else that comes to mind. Be creative! 3. Once your full-sentence outline is completed, you can start rehearsing your speech. Be sure that your speech is not written out word-for-word; for extemporaneous speaking, you want your outline to be as concise as possible so that you can develop a more conversational style of delivery. 4. As you rehearse your speech, you should make adjustments and changes. If you’re confident enough, condense your full sentence outline into a speaking outline, such that it includes only your basic speech structure and key phrases and details....

Words: 814 - Pages: 4

Premium Essay

English 216

...This is a two part question. I need an outline created then a final draft for a project on turnover rates. The two files that are attached show the requirements and the second one is the outline template that HAS to be used. The two items are based off the following question: Employee turnover rates are high for many organizations, and you have noticed that the company you work for is no different. Research what other organizations are doing to hire and retain good employees in order to combat the high employee turnover rate. Use this research to make recommendations to the management of your organization. ENGL 216 Formal Report/Proposal Outline Template Your name: Directions: Refer to your textbook (Chapter 2, page 48 and Chapter 10, page 311) and the Week 4 Lecture to complete this outline. Write in complete sentences, not single words or short phrases. Be as detailed as possible, adding in-text citations for all references noted on your References page from Week 3, which should also be included here. The more information you place in this final outline, the less work you will have to do for the report drafts. Introduction: This section sets the stage and purpose of the report. See page 320 in the text for help in completing this section. (Minimum of one sentence per point) Purpose: Description/Background: Find the best study resources around, tagged to your specific courses. Share your own to gain free Course Hero access or to earn money with our Marketplace...

Words: 263 - Pages: 2

Premium Essay

Explosion System

...Personnel Personnel are one of the factors that are considered when selecting an explosion suppression system. Two considerations are the proximity of personnel to the protected equipment, and the risk of personnel exposure to the suppression agent selected. In order to understand how personnel can be affected by explosion suppression systems, and why personnel are a factor when considering an explosion suppression system, you must first understand what makes up an explosion suppression system and how it functions. Explosion suppression systems are comprised of a cylinder containing the suppressing agent, a detection system, and control circuitry. During the incipient stages of a deflagration, the detection system triggers the cylinder to release the suppressing agent into the protected system or vessel, suppressing the deflagration. It is important to note that explosion suppression systems are intended to protect vessels or other enclosed areas in which over-pressurization is the primary concern. When the pressure is released in these systems, it is also important to ensure that personnel are not within the proximity of area in which the pressure increases (FM Approvals, 1999). The agent selected for explosion protection is another important factor when considering an explosion protection system. There are three agents most commonly used, and they may have different effects on personnel if they come into contact with the substances when the system is activated (Gagnon...

Words: 481 - Pages: 2

Free Essay

Mission

...However, as I’m coming close to the end of my college career I realized I was wrong. Nonetheless, looking at my freshman essay now, I do see how I’ve grown within these past for years. Within my freshman year, I realized didn’t take the time to actually analyze my topic to where I could have understand it more. Therefore, it didn’t come out the way that I’ve envisioned it to be. The topic of evil is a widespread and extensive topic. If I was to approach this topic now, I would have done more extensive research on the nature of evil. This would have made me more knowledgeable about the topic at hand and helped me determine how to start this paper. In addition, before beginning this essay, I should have created an outline to help guide me throughout my paper. The outline would have given me the opportunity go through the research that I’ve gathered and helped to be more critical on how I wanted to present evil and it’s different levels. Doing this would have help me to develop this essay within a more critical and organize matter. While reading my freshman essay, I find myself coming up with more ideas of how I could have develop my point of view of the branches of evil, hence making an stronger argument. For example, I should have went into more deal of the ways evil is view within religion and our society. By doing this, it would have gave a more insight to the reader of how the paper is developing. This also would have given the reader an additional understanding of what evil...

Words: 398 - Pages: 2

Free Essay

Com150 Appendix D

...Appendix D Topic Outline and Thesis Statement Guide My thesis is : Even though most people think that tattoos and piercings are known to be unholy, there are a lot people in the world today who strongly believe that they are meant to be pictures of art from personal feelings such as personal histories, special events, or past/present experiences in their lives. ________________________________ I. All Peoples views on tattoos in today’s world A. many people view tattoos as good/or bad 1. Most People view tattoos as being unholy 2. Younger people view tattoos as being a form of art B. Why most people view tattoos as being bad 1. Tattoo’s are unholy 2. Many people believe you are to treat your body as a temple II. Effects of tattoos A. How tattoos effects you 1. Tattoos are feelings of art, or personal experiences 2. Help people express their selves with pictures B. How tattoos effects other people 1. People may dislike you 2. People may feel angry III. Cost of tattoos in today’s world A. Are tattoos worth a lot of money? 1. How expensive are tattoos 2. What do you get for your money? B. Do teenagers spend all of their money on getting tattoos? 1. How much do teenagers spend? 2. How many teenagers get tattoos, and why? IV. Health Risks and prevention from tattoos A. What are the health risks of getting Tattoo’s? 1. Blood Bourne diseases 2. Skin disorders and infections 3. Allergic reactions ...

Words: 259 - Pages: 2