Programi Kryesor
public class programipare { public static void main(String[] args){ System.out.println("Ky eshte programi jone i pare"); } }
Program qe merr te dhenat nga tastiera
import java.util.Scanner; public class Impact { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.print("Vendos nje numer: "); int num = scan.nextInt(); scan.close(); System.out.println("Numri qe ju vendoset eshte: "+num); } }
Shumezimi i dy numrave
import java.util.Scanner; public class Impact2 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.print("Vendos nr e pare: "); int num1 = scan.nextInt(); System.out.print("Vendos nr e dyte: "); int num2 = scan.nextInt(); scan.close(); int product = num1*num2; System.out.println("Rezultati: "+product); } }
Siperfaqja dhe perimetri i rrethit
import java.util.Scanner; class CircleImpact { static Scanner sc = new Scanner(System.in); public static void main(String args[]) { System.out.print("Vendos Rrezen: "); double radius = sc.nextDouble(); //Siperfaqja = PI*radius*radius double area = Math.PI * (radius * radius); System.out.println("Siperfaqja e rrethit: " + area); //Perimetri = 2*PI*radius double circumference= Math.PI * 2*radius; System.out.println( "Perimetri eshte:"+circumference) ; } }
Numrat tek ose Cift me kushtin if-else
import java.util.Scanner; class KontrolloEvenOdd { public static void main(String args[]) { int num; System.out.println("Vendos nje numer te plote:"); Scanner input = new Scanner(System.in); num = input.nextInt(); if ( num % 2 == 0 ) System.out.println("Numri i vendosur eshte cift"); else System.out.println("Numri i vendosur eshte tek"); } }
public class Nqs { public static void main(String[] args) { //variabli i moshes int mosha=20; if(mosha>18){ System.out.print("Urime jeni me shume se 18"); } else { System.out.print("Ju nuk jeni me shume se 18"); } } } ____________________________________________ public class KushtetNested { public static void main(String[] args) { int mosha=20; int pesha=80; if(mosha>=18){ if(pesha>50){ System.out.println("Ju mund te jepni gjak"); } } }} ____________________________________________ public class KushtetNested2 { public static void main(String[] args) { int mosha=25; int pesha=48; if(mosha>=18){ if(pesha>50){ System.out.println("Ju mund te jepni gjak"); } else{ System.out.println("Ju nuk mund te jepni gjak"); } } else{ System.out.println("Mosha juaj duhet te jete me e madhe se 18"); } } } ____________________________________________ public class SwitchShembull { public static void main(String[] args) { int numer=20; switch(numer){ case 10: System.out.println("10"); break; case 20: System.out.println("20"); break; case 30: System.out.println("30"); break; default:System.out.println("jo ne 10, 20 ose 30"); } } } ____________________________________________ public class SwitchZanoret { public static void main(String[] args) { char ch='O'; switch(ch) { case 'a': System.out.println("zanore"); break; case 'e': System.out.println("zanore"); break; case 'i': System.out.println("zanore"); break; case 'o': System.out.println("zanore"); break; case 'u': System.out.println("zanore"); break; case 'A': System.out.println("zanore"); break; case 'E': System.out.println("zanore"); break; case 'I': System.out.println("zanore"); break; case 'O': System.out.println("zanore"); break; case 'U': System.out.println("zanore"); break; default: System.out.println("Bashktingellore"); } } } ____________________________________________ public class ForShembull{ public static void main(String[] args) { for(int i=1;i<=10;i++){ System.out.println(i); } } } ____________________________________________ public class DoWhileShembull { public static void main(String[] args) { int i=1; do{ System.out.println(i); i++; }while(i<=10); } } ____________________________________________ class FibonacciShembulli{ public static void main(String args[]) { int n1=0,n2=1,n3,i,count=10; System.out.print(n1+" "+n2); for(i=2;i<count;++i) { n3=n1+n2; System.out.print(" "+n3); n1=n2; n2=n3; } }} ____________________________________________ class FibonacciShembulli2{ static int n1=0,n2=1,n3=0; static void printFibonacci(int count){ if(count>0){ n3 = n1 + n2; n1 = n2; n2 = n3; System.out.print(" "+n3); printFibonacci(count-1); } } public static void main(String args[]){ int count=10; System.out.print(n1+" "+n2); printFibonacci(count-2); } }
import java.util.Scanner; public class ushtr2 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Vendos 10 numra: "); int[] n = new int[10]; // Kalon vlerat e input ne array for (int i = 0; i < 10; i++) n[i] = input.nextInt(); // Afishon array ne reverse for (int i = n.length - 1; i >= 0; i--) System.out.print(n[i] + " "); } } _________________________________________________________________ class Ladder { public static void main(String[] args) { int number = 0; if (number > 0) { System.out.println("Numri eshte pozitiv."); } else if (number < 0) { System.out.println("Numri eshte negativ."); } else { System.out.println("Numri eshte 0."); } } } _________________________________________________________________ class Dita { public static void main(String[] args) { int java = 4; String dita; switch (java) { case 1: dita = "Hene"; break; case 2: dita = "Mart"; break; case 3: dita = "Merkur"; break; case 4: dita = "Enjte"; break; case 5: dita = "Premte"; break; case 6: dita = "Shtune"; break; case 7: dita = "Diel"; break; default: dita = "Nuk ka kshu dite !"; break; } System.out.println(dita); } } _________________________________________________________________ import java.util.Scanner; class Calculator { public static void main(String[] args) { char operator; Double numri1, numri2, rezultati; Scanner scanner = new Scanner(System.in); System.out.print("Vendos (ose +, -, * ose /): "); operator = scanner.next().charAt(0); System.out.print("Vendos numri1 dhe numri2 sipas radhes: "); numri1 = scanner.nextDouble(); numri2 = scanner.nextDouble(); switch (operator) { case '+': rezultati = numri1 + numri2; System.out.print(numri1 + "+" + numri2 + " = " + rezultati); break; case '-': rezultati = numri1 - numri2; System.out.print(numri1 + "-" + numri2 + " = " + rezultati); break; case '*': rezultati = numri1 * numri2; System.out.print(numri1 + "*" + numri2 + " = " + rezultati); break; case '/': rezultati = numri1 / numri2; System.out.print(numri1 + "/" + numri2 + " = " + rezultati); break; default: System.out.println("Ju lutem vendosni sakte!"); break; } } }
class Testarray{ public static void main(String args[]){ int a[]=new int[5];//deklarimi i array a[0]=10;//Inicializimi a[1]=20; a[2]=70; a[3]=40; a[4]=50; //leximi i array behet vetem me for for(int i=0;i<a.length;i++)//length eshte gjatesia e array System.out.println(a[i]); }} ________________________________________________________________ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ________________________________________________________________ public class CopyArray { public static void main(String[] args) { //Inicializimi array int [] arr1 = new int [] {1, 2, 3, 4, 5}; //Krijimi i array arr2 me madhesine e array arr1 int arr2[] = new int[arr1.length]; //Kopjimi i elementeve tek array tjeter for (int i = 0; i < arr1.length; i++) { arr2[i] = arr1[i]; } //Shfaq elementet e array 1 System.out.println("Elementet e array origjinal: "); for (int i = 0; i < arr1.length; i++) { System.out.print(arr1[i] + " "); } System.out.println(); //Shfaq elementet e array 2 System.out.println("Elementet e array te ri: "); for (int i = 0; i < arr2.length; i++) { System.out.print(arr2[i] + " "); } } } ________________________________________________________________ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ________________________________________________________________ public class ShumaeArray { public static void main(String[] args) { //Inicializimi i array int [] arr = new int [] {1, 2, 3, 4, 5}; int sum = 0; //Shuma ndodh duke bredhur cdo element brenda array me [i] for (int i = 0; i < arr.length; i++) { sum = sum + arr[i]; } System.out.println("Shuma e elementeve eshte: " + sum); } } ________________________________________________________________ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ________________________________________________________________ import java.util.Scanner; public class Nota_Studenteve { public static void main(String[] args) { int n, total = 0, perqindje; Scanner s = new Scanner(System.in); System.out.print("Vendos nr e lendeve:"); n = s.nextInt(); int marks[] = new int[n]; System.out.println("Vendosni piket deri 1000:"); for(int i = 0; i < n; i++) { marks[i] = s.nextInt(); total = total + marks[i]; } perqindje = total / n; System.out.println("Shuma:"+total); System.out.println("Perqindja eshte :"+perqindje); } } ________________________________________________________________ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ________________________________________________________________ import java.util.Scanner; public class Cift_Tek { public static void main(String[] args) { int n; Scanner s = new Scanner(System.in); System.out.print("Vendos nr sa element do jene:"); n = s.nextInt(); int a[] = new int[n]; System.out.println("Vendos te gjithe elementet:"); for (int i = 0; i < n; i++) { a[i] = s.nextInt(); } System.out.print("Nr tek:"); for(int i = 0 ; i < n ; i++) { if(a[i] % 2 != 0) { System.out.print(a[i]+" "); } } System.out.println(""); System.out.print("Nr Cift:"); for(int i = 0 ; i < n ; i++) { if(a[i] % 2 == 0) { System.out.print(a[i]+" "); } } } }
//Merr 10 nr nga tastiera dhe printoji import java.util.*; class Ans{ public static void main(String[] args){ Scanner s = new Scanner(System.in); int[] z = new int[10]; for(int i = 0;i<z.length;i++){ System.out.println("Pronto vleren e z["+i+"]"); z[i] = s.nextInt(); } for(int i = 0;i<z.length;i++){ System.out.println("Vlera e z ["+i+"] eshte "+z[i]); } } } _______________________________________________________________________ ======================================================================= _______________________________________________________________________ //Gjej elementin me te madh dhe me te vogel ne nje array import java.util.*; class Ans{ public static void main(String[] args){ Scanner s = new Scanner(System.in); int[] a = new int[10]; for(int i =0;i<a.length;i++){ System.out.println("Vendos nje numer a["+i+"]"); a[i] = s.nextInt(); } int madhi = a[0]; int vogli = a[0]; for(int i = 0;i<a.length;i++){ if(a[i]>madhi) madhi = a[i]; if(a[i]<vogli) vogli = a[i]; } System.out.println("Me i madhi eshte "+madhi+" dhe me i vogli eshte "+vogli); } } _______________________________________________________________________ ======================================================================= _______________________________________________________________________ //Identifiko nr qe mungon ne nje array public class Humbur { static int gjejNrHumbur (int a[], int n) { int i, total; total = (n + 1) * (n + 2) / 2; for ( i = 0; i < n; i++) total -= a[i]; return total; } public static void main(String... s) { int a[ ] = {1, 2, 4, 5, 6}; int miss = gjejNrHumbur(a, 5); System.out.println("Nr qe mungon eshte :"+miss); } } _______________________________________________________________________ ======================================================================= _______________________________________________________________________ //Mesatarja e studenteve me funksion class GjejMesataren { static double mesatarja(int a[], int n) { // shuma e elemteve int shuma = 0; for (int i = 0; i < n; i++) shuma += a[i]; return (double)shuma / n; } public static void main (String[] args) { int arr[] = {10, 2, 3, 4, 5, 6, 7, 8, 9}; int n = arr.length; System.out.println(mesatarja(arr, n)); } } _______________________________________________________________________ ======================================================================= _______________________________________________________________________ //For Each loop class Main { public static void main(String[] args) { // Krijimi array int[] numbers = {3, 9, 5, -5}; // for each for (int number: numbers) { System.out.println(number); } } } ____________________________________________________ ____________________________________________________ //// Shuma e elementeve ne nje array class Main { public static void main(String[] args) { // deklarimi array int[] numbers = {3, 4, 5, -5, 0, 12}; int shuma = 0; // iteracioni ne te gjithe nr for (int number: numbers) { shuma += number; } System.out.println("Shuma = " + shuma); } } ____________________________________________________ ____________________________________________________ //afishimi zanoreve class Main { public static void main(String[] args) { char[] vowels = {'a', 'e', 'i', 'o', 'u'}; // krijimi for each for (char item: vowels) { System.out.println(item); } } } ____________________________________________________ ____________________________________________________ //Kontrollo nese nje vlere eshte ne array public class Contains { public static void main(String[] args) { int[] num = {1, 2, 3, 4, 5}; int gjej = 3; boolean uGjet = false; for (int n : num) { if (n == gjej) { uGjet = true; break; } } if(uGjet) System.out.println(gjej + " eshte ne array"); else System.out.println(gjej + " nuk eshte ne array"); } } ____________________________________________________ ____________________________________________________
//Gjej Gabimet int a= new int(5); for(int i=0; i<=5; i++) a[i]= I; __________________________________________________________ __________________________________________________________ //Cfare Afishon int mat[ ][ ]= {{13,64},{77,46}}; for(int x=0;x<2;x++){ for(int y= 0; y<2; y++) System.out.print(mat[x][y]+ " "); System.out.println(); __________________________________________________________ __________________________________________________________ //Update vleren me +10 int m[ ]= {4, 6, 8, 12, 16, 3, 9, 7 }; __________________________________________________________ __________________________________________________________ //Rregulloni sintaksen Class First { public static void main(String args[]) { int sum[2,4]; for(i=0;i<2;i++) { for(j=0;j<=3;j++) { System.print(sum); } } } } __________________________________________________________ __________________________________________________________ //Identifiko Erroret class First { public static void main(String args[]) { int i; int a[6]={0,1,8,7,6,4}; for(i=0;i<=a.length();i++) System.out.println(a[i]); } }
import java.util.Scanner; public class shummatrica { public static void main(String[] args) { System.out.println("Vendosni nr e rrjeshtave te matrix"); Scanner sc = new Scanner(System.in); int rrjesht = sc.nextInt(); System.out.println("Vendosni nr e kolonave te matrix"); int kolone = sc.nextInt(); int[][] first = new int[rrjesht][kolone]; int[][] second = new int[rrjesht][kolone]; //hedhja e elementeve te matrices 1 for (int r = 0; r < rrjesht; r++) { for (int c = 0; c < kolone; c++) { System.out.println(String.format("Vendos matrix e pare [%d][%d] te plote", r, c)); first[r][c] = sc.nextInt(); } } //hedhja e elementeve te matrices 2 for (int r = 0; r < rrjesht; r++) { for (int c = 0; c < kolone; c++) { System.out.println(String.format("Matrixa e dyte[%d][%d] nr te plote", r, c)); second[r][c] = sc.nextInt(); } } //ndares gjejme te transpozuaren int transpose[][]=new int[rrjesht][kolone]; for(int i=0;i<rrjesht;i++){ for(int j=0;j<kolone;j++){ transpose[i][j]=first[j][i]; } } System.out.println("Printimi i transpozimit te matrices:"); for(int i=0;i<rrjesht;i++){ for(int j=0;j<kolone;j++){ System.out.print(transpose[i][j]+" "); } System.out.println();//new line } //ndares per te gjetur shumen int[][] sum = new int[rrjesht][kolone]; for (int r = 0; r < rrjesht; r++) { for (int c1 = 0; c1 < kolone; c1++) { sum[r][c1] = first[r][c1] + second[r][c1]; } } System.out.println("shuma e matricave:"); for (int r = 0; r < sum.length; r++) { for (int c1 = 0; c1 < sum[0].length; c1++) { System.out.print(sum[r][c1] + "t"); } System.out.println(); } //ndares per te gjetur shumezimin System.out.println("shumezimi i matricave:"); int[][] c = new int[rrjesht][kolone]; for(int i = 0; i < rrjesht; i++) { for (int j = 0; j < kolone; j++) { c[i][j]=0; for(int k=0;k<kolone;k++) { c[i][j]+=first[i][k]*second[k][j]; }//end of k loop System.out.print(c[i][j]+" "); //printing matrix element }//end of j loop System.out.println();//new line } //ndares per te afishuar elementet e siperm te diagonales kryesore if(rrjesht != kolone){ System.out.println("Matrica duhet te jete katrore"); } else { System.out.println("Afisho matricen e siperme: "); for(int i = 0; i < rrjesht; i++){ for(int j = 0; j < kolone; j++){ if(i > j) System.out.print("0 "); else System.out.print(first[i][j] + " "); } System.out.println(); } } //ndares per te afishuar elementet te diagonales kryesore if(rrjesht != kolone){ System.out.println("Matrica duhet te jete katrore"); } else { System.out.println("Afisho vetem diagonalen: "); for(int i = 0; i < rrjesht; i++){ for(int j = 0; j < kolone; j++){ if(i == j) System.out.print(first[i][j] + " "); else System.out.print("0 "); } System.out.println(); } } sc.close(); } }
//Program i cili numeron fjalet ne nje fjali import java.util.Scanner; public class Exercise5 { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Vendos nje fjali: "); String str = in.nextLine(); System.out.print("Numri fjaleve ne fjali: " + count_Words(str)+"n"); } public static int count_Words(String str) { int count = 0; if (!(" ".equals(str.substring(0, 1))) || !(" ".equals(str.substring(str.length() - 1)))) { for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == ' ') { count++; } } count = count + 1; } return count; } } __________________________________________________________________ __________________________________________________________________ //Konverto fjalet me te vogla ne me te medhaja public class Exercise30 { public static void main(String[] args) { String str = "Impact Education! Impact your Future!"; String upper_str = str.toUpperCase(); System.out.println("Stringu origjinal: " + str); System.out.println("Stringu me shkronja te medha : " + upper_str); } } __________________________________________________________________ __________________________________________________________________ //Konverto string ne Int public class konvertostring{ public static void main(String args[]){ String str="123"; int inum = 100; int inum2 = Integer.parseInt(str);//konverton stringun ne int int sum = inum+inum2; System.out.println("Shuma eshte: "+sum); } }
class subClass extends superClass { //methods and fields } _______________________________________________________ ======================================================= _______________________________________________________ //name.java public class Name { public void display() { System.out.println("Impact Education"); } } // filename: DisplayName.java // Krijoji ne te njejtin folder // Clasa permban metoden main() public class DisplayName { public static void main(String[] args) { Name emriim = new Name(); emriim.display(); } } _______________________________________________________ ======================================================= _______________________________________________________ public class KlasaIme{ int x = 5; public static void main(String[] args) { KlasaIme obj1= new KlasaIme(); // Objekti 1 KlasaIme obj2= new KlasaIme(); // Objekti 2 System.out.println(obj1.x); System.out.println(obj2.x); } } public class KlasaIme{ int x = 5; public static void main(String[] args) { KlasaIme obj1 = new KlasaIme(); // Objekti 1 KlasaIme obj2= new KlasaIme(); // Objekti 2 obj2.x = 25; System.out.println(obj1.x); // Afishon 5 System.out.println(obj2.x); // Afishon 25 } _______________________________________________________ ======================================================= _______________________________________________________ public class Makina { int vitiModelit; String emriModelit; public Makina (int viti, String emri) { vitiModelit= viti; emriModelit= emri; } public static void main(String[] args) { Makina makinaIme= new Makina(1969, "Mustang"); System.out.println(makinaIme.vitiModelit+ " " + makinaIme.emriModelit); } } // Afishon: 1969 Mustang class Automjeti { protected String modeli= "Ford"; public void buria() { System.out.println("Tuut, tuut!"); } } class Automjeti extends Automjeti { private String modeliEmri= "Mustang"; public static void main(String[] args) { Automjeti makinaimeShpejte= new Automjeti(); makinaimeShpejte.buria(); System.out.println(makinaimeShpejte.modeli+ " " + makinaimeShpejte.modeliEmri); } } _______________________________________________________ ======================================================= _______________________________________________________ //filename: Account.java public class Account { private double balance; public Account(double initialBalance) { if (initialBalance > 0.0) balance=initialBalance; } public void credit(double amount){ balance=balance+amount; } public void debit(double amount){ balance=balance-amount; } public double getBalance(){ return balance; } } //filename: AccountTest.java import java.util.Scanner; public class AccountTest { public static void main (String args[]){ Account account1 = new Account (50.00); Account account2 = new Account (-7.53); System.out.printf("Account1 Balance: $%.2fn", account1.getBalance()); System.out.printf("Account2 Balance: $%.2fnn", account2.getBalance()); Scanner input = new Scanner( System.in ); double depositAmount; double debitAmount; System.out.print( "Enter deposit amount for account1: " ); // prompt depositAmount = input.nextDouble(); // obtain user input System.out.printf( "nadding %.2f to account1 balancenn", depositAmount ); account1.credit( depositAmount ); // add to account1 balance // display balances System.out.printf( "Account1 balance: $%.2fn", account1.getBalance() ); System.out.printf( "Account2 balance: $%.2fnn", account2.getBalance() ); System.out.print( "Enter deposit amount for account2: " ); // prompt depositAmount = input.nextDouble(); // obtain user input System.out.printf( "nAdding %.2f to account2 balancenn", depositAmount ); account2.credit( depositAmount ); // add to account2 balance // display balances System.out.printf( "Account1 balance: $%.2fn", account1.getBalance() ); System.out.printf( "Account2 balance: $%.2fn", account2.getBalance() ); System.out.print( "Enter debit amount for account1: " ); debitAmount = input.nextDouble(); System.out.printf( "nSubtracting %.2f from account1 balancenn", debitAmount ); if (account1.getBalance()>=debitAmount) { account1.debit( debitAmount ); System.out.printf( "Account1 balance: $%.2fn", account1.getBalance() ); System.out.printf( "Account2 balance: $%.2fnn", account2.getBalance() ); } else { System.out.printf("!!! Debit amount exceeded account balance!!!nn"); } // display balances System.out.print( "Enter debit amount for account2: " ); debitAmount = input.nextDouble(); System.out.printf( "nSubtracting %.2f from account2 balancenn", debitAmount ); if (account1.getBalance()>=debitAmount) { account1.debit( debitAmount ); System.out.printf( "Account1 balance: $%.2fn", account1.getBalance() ); System.out.printf( "Account2 balance: $%.2fnn", account2.getBalance() ); } else { System.out.printf("!!!Debit amount exceeded account balance!!!nn"); } } } _______________________________________________________ ======================================================= _______________________________________________________ //filename: Invoice.java // Invoice class public class Invoice { private String partNumber; private String partDescription; private int quantity; private double price; public Invoice(String pNum, String pDesc, int qty, double prc) { if (pNum != null) partNumber=pNum; else partNumber="0"; if (pDesc != null) partDescription=pDesc; else partDescription="0"; if (qty > 0) quantity=qty; else quantity=0; if (prc > 0.0) price=prc; else price=0; } public String getPartNum(){ return partNumber; } public String getPartDesc(){ return partDescription; } public int getQuantity(){ return quantity; } public double getPrice(){ return price; } public void setPartNum(String pNum){ if (pNum != null) {partNumber=pNum;} else {partNumber="0";} } public void setPartDesc(String pDesc){ if (pDesc != null) {partDescription=pDesc;} else {partDescription="0";} } public void setQuantity(int qty){ if (qty > 0) {quantity=qty;} else {quantity=0;} } public void setPrice(double prc){ if (prc > 0.0) {price=prc;} else {price=0.0;} } public double getInvoiceAmount(){ return (double)quantity*price; } } //filename: InvoiceTest.java // Invoice testing class with the main() method public class InvoiceTest { public static void main (String args[]){ Invoice invoice1=new Invoice ("A5544", "Big Black Book", 500, 250.00); Invoice invoice2=new Invoice ("A5542", "Big Pink Book", 300, 50.00); System.out.printf("Invoice 1: %st%st%dt$%.2fn", invoice1.getPartNum(), invoice1.getPartDesc(), invoice1.getQuantity(), invoice1.getPrice()); System.out.printf("Invoice 2: %st%st%dt$%.2fn", invoice2.getPartNum(), invoice2.getPartDesc(), invoice2.getQuantity(), invoice2.getPrice()); } }
//Polimorfizmi lejon te perdoret e njejta metod per veprime te ndryshme class Animal { public void animalSound() { System.out.println("The animal makes a sound"); } } class Pig extends Animal { public void animalSound() { System.out.println("The pig says: wee wee"); } } class Dog extends Animal { public void animalSound() { System.out.println("The dog says: bow wow"); } } class Main { public static void main(String[] args) { Animal myAnimal = new Animal(); // Create a Animal object Animal myPig = new Pig(); // Create a Pig object Animal myDog = new Dog(); // Create a Dog object myAnimal.animalSound(); myPig.animalSound(); myDog.animalSound(); } } __________________________________________________________________ ================================================================== __________________________________________________________________ //Animal.java public class Animal{ public void sound(){ System.out.println("Animal is making a sound"); } } //Horse.java class Horse extends Animal{ @Override public void sound(){ System.out.println("Neigh"); } public static void main(String args[]){ Animal obj = new Horse(); obj.sound(); } } //Cat.java public class Cat extends Animal{ @Override public void sound(){ System.out.println("Meow"); } public static void main(String args[]){ Animal obj = new Cat(); obj.sound(); } }
//Punetor.java public class Punetor { private String emriPare; private String mbiemriPare; private double rroga; public Punetor(String ePare, String mPare, double rro) { if (ePare != null) emriPare =ePare; if (mPare != null) mbiemriPare = mPare; if (rro > 0.0) { rroga=rro; } else { rroga=0.0; } } //set methods public String getEmriPare(){ return emriPare; } public String getMbiemriPare(){ return mbiemriPare; } public double getRroga(){ return rroga; } //get methods public void setEmriPare(String ePare){ if (ePare != null) emriPare = ePare; } public void setMbiemriPare(String mPare){ if (mPare != null) mbiemriPare = mPare; } public void setRroga(double rro){ if (rro > 0.0){ rroga = rro; } else { rroga = 0.0; } } } _______________________________________________ =============================================== _______________________________________________ //Klasa e punetorit, ku do bejme rritjen e rroges me 10% public class punetorTest { public static void main (String args[]){ Punetor Punetor1=new Punetor ("Said", "Dulevic", 20000.00); Punetor Punetor2=new Punetor ("Impact", "Education", 50000.00); System.out.printf("nNO:t EMRItttRROGA VJETOREnn"); System.out.printf("--t ----ttt-------------n"); System.out.printf("1:t %s %stt$%.2fn", Punetor1.getEmriPare(), Punetor1.getMbiemriPare(), Punetor1.getRroga()); System.out.printf("2:t %s %stt$%.2fn", Punetor2.getEmriPare(), Punetor2.getMbiemriPare(), Punetor2.getRroga()); //rrit rrogen me 10% Punetor1.setRroga( (.1*Punetor1.getRroga())+Punetor1.getRroga()); Punetor2.setRroga( (.1*Punetor2.getRroga())+Punetor2.getRroga()); System.out.printf("n10U rrit rroga me 10%!! Yoohooooo!n"); System.out.printf("nNO:t EmritttRROGA VJETOREn"); System.out.printf("--t ----ttt-------------n"); System.out.printf("1:t %s %stt$%.2fn", Punetor1.getEmriPare(), Punetor1.getMbiemriPare(), Punetor1.getRroga()); System.out.printf("2:t %s %stt$%.2fn", Punetor2.getEmriPare(), Punetor2.getMbiemriPare(), Punetor2.getRroga()); } } _______________________________________________ =============================================== _______________________________________________ //filename: Date.java // Date class public class Date { private int month; private int day; private int year; public Date(int myMonth,int myDay, int myYear) { month = myMonth; day = myDay; year = myYear; } public void setMonthDate(int myMonth) { month = myMonth; } public int getMonthDate() { return month; } public void setDayDate(int myDay) { day = myDay; } public int getDayDate() { return month; } public void setYearDate(int myYear) { year = myYear; } public int getYearDate() { return year; } public void displayDate() { System.out.printf("%d/%d/%d", month,day,year); } _______________________________________________ //filename: DateTest.java // Date testing class with the main() method import java.util.*; public class DateTest { public static void main(String[] args) { Scanner input = new Scanner(System.in); Date myDate = new Date(9, 11, 1986); System.out.println("Enter The Month"); int myMonth = input.nextInt(); myDate.setMonthDate(myMonth); System.out.println("Enter the Date"); int myDay = input.nextInt(); myDate.setDayDate(myDay); System.out.println("Enter the Year"); int myYear = input.nextInt(); myDate.setYearDate(myYear); myDate.displayDate(); } } _______________________________________________ =============================================== _______________________________________________ //filename: SavingAccount.java // SavingAccount class public class SavingsAccount { public static double annualInterestRate; private double savingsBalance; public SavingsAccount() { annualInterestRate = 0.0; savingsBalance = 0.0; } public SavingsAccount(double intRate, double savBal) { annualInterestRate = intRate; savingsBalance = savBal; } public double calculateMonthlyInterest() { double intRate = (savingsBalance * annualInterestRate/12); savingsBalance = savingsBalance + intRate; return intRate; } public static void modifyInterestRate(double newInteresRate) { annualInterestRate = newInteresRate; } public void setSavingsBalance(double newBal) { savingsBalance = newBal; } public double getSavingsBalance() { return savingsBalance; } public double getAnnualInterestRate() { return annualInterestRate; } } _______________________________________________ //filename: SavingsAccountTest.java // SavingsAccount testing class with the main() method public class SavingsAccountTest { public static void main(String[] args) { SavingsAccount saver1 = new SavingsAccount(); SavingsAccount saver2 = new SavingsAccount(); saver1.setSavingsBalance(2000.00); saver2.setSavingsBalance(3000.00); SavingsAccount.modifyInterestRate(0.04); saver1.calculateMonthlyInterest(); saver2.calculateMonthlyInterest(); System.out.printf("New Balance for Saver1=%fn",saver1.getSavingsBalance()); System.out.printf("New Balance for Saver2=%fn",saver2.getSavingsBalance()); SavingsAccount.modifyInterestRate(0.05); saver1.calculateMonthlyInterest(); saver2.calculateMonthlyInterest(); System.out.printf("New Balance for Saver1=%fn",saver1.getSavingsBalance()); System.out.printf("New Balance for Saver2=%fn",saver2.getSavingsBalance()); } } _______________________________________________ =============================================== _______________________________________________ //filename: Book.java // Book class public class Book { private String Name; private String ISBN; private String Author; private String Publisher; public Book() { Name = "NULL"; ISBN = "NULL"; Author = "NULL"; Publisher = "NULL"; } public Book(String name, String isbn, String author, String publisher) { Name = name; ISBN = isbn; Author = author; Publisher = publisher; } public void setName(String Name) { this.Name = Name; } public String getName() { return Name; } public void setISBN(String ISBN) { this.ISBN = ISBN; } public String getISBN() { return ISBN; } public void setAuthor(String Author) { this.Author = Author; } public String getAuthor() { return Author; } public void setPublisher(String Publisher) { this.Publisher = Publisher; } public String getPublisher() { return Publisher; } public void getBookInfo() { System.out.printf("%s %s %s %s", Name,ISBN,Author,Publisher); } } _______________________________________________ //filename: SavingsAccountTest.java // SavingsAccount testing class with the main() method public class BookTest { public static void main(String[] args) { Book test[] = new Book[13]; test[1] = new Book(); test[1].getBookInfo(); } } _______________________________________________ =============================================== _______________________________________________
a. Create a super class called Car. The Car class has the following fields and methods. ◦intspeed; ◦doubleregularPrice; ◦Stringcolor; ◦doublegetSalePrice(); ______________________________________________________ //filename: Car.java //Car class public class Car { private int speed; private double regularPrice; private String color; public Car (int Speed,double regularPrice,String color) { this.speed = Speed; this.regularPrice = regularPrice; this.color = color; } public double getSalePrice() { return regularPrice; } } ______________________________________________________ b. Create a sub class of Car class and name it as Truck. The Truck class has the following fields and methods. ◦intweight; ◦doublegetSalePrice();//Ifweight>2000,10%discount.Otherwise,20%discount. ______________________________________________________ //filename: Truck.java // Truck class, subclass of Car public class Truck extends Car { private int weight; public Truck (int Speed,double regularPrice,String color, int weight) { super(Speed,regularPrice,color); this.weight = weight; } public double getSalePrice() { if (weight > 2000){ return super.getSalePrice() - (0.1 * super.getSalePrice()); } else { return super.getSalePrice(); } } } ______________________________________________________ c. Create a subclass of Car class and name it as Ford. The Ford class has the following fields and methods ◦intyear; ◦intmanufacturerDiscount; ◦doublegetSalePrice(); //FromthesalepricecomputedfromCarclass,subtractthemanufacturerDiscount. ______________________________________________________ //filename: Ford.java // Ford class, subclass of Car public class Ford extends Car { private int year; private int manufacturerDiscount; public Ford (int Speed,double regularPrice,String color, int year, int manufacturerDiscount) { super (Speed,regularPrice,color); this.year = year; this.manufacturerDiscount = manufacturerDiscount; } public double getSalePrice() { return (super.getSalePrice() - manufacturerDiscount); } } ______________________________________________________ d. Create a subclass of Car class and name it as Sedan. The Sedan class has the following fields and methods. ◦intlength; ◦doublegetSalePrice(); //Iflength>20feet,5%discount,Otherwise,10%discount. ______________________________________________________ //filename: Sedan.java // Sedan class, subclass of Car public class Sedan extends Car { private int length; public Sedan (int Speed,double regularPrice,String color, int length) { super (Speed,regularPrice,color); this.length = length; } public double getSalePrice() { if (length > 20) { return super.getSalePrice() - (0.05 * super.getSalePrice()); } else { return super.getSalePrice() - (0.1 * super.getSalePrice()); } } } ______________________________________________________ e. Create MyOwnAutoShop class which contains the main() method. Perform the following within the main() method. ◦Create an instance of Sedan class and initialize all the fields with appropriate values. Use super(...) method in the constructor for initializing the fields of the superclass. ◦Create two instances of the Ford class and initialize all the fields with appropriate values. Use super(...) method in the constructor for initializing the fields of the super class. ◦Create an instance of Car class and initialize all the fields with appropriate values. Display the sale prices of all instance. ______________________________________________________ //filename: MyOwnAutoShop.java // Testing class with the main() method public class MyOwnAutoShop { (int Speed,double regularPrice,String color, int year, int manufacturerDiscount) public static void main(String[] args) { Sedan mySedan = new Sedan(160, 20000, "Red", 10); Ford myFord1 = new Ford (156,4452.0,"Black",2005, 10); Ford myFord2 = new Ford (155,5000.0,"Pink",1998, 5); Car myCar - new Car (555, 56856.0, "Red"); System.out.printf("MySedan Price %.2f", mySedan.getSalePrice()); System.out.printf("MyFord1 Price %.2f", myFord1.getSalePrice()); System.out.printf("MyFord2 Price %.2f", myFord2.getSalePrice()); System.out.printf("MyCar Price %.2f", myCar.getSalePrice()); } }
____________________________________________________ ==================================================== ____________________________________________________ import java.awt.*; import javax.swing.*; public class Test extends JFrame { JLabel no1 = new JLabel("Number 1"); JLabel no2 = new JLabel("Number 2"); JLabel sum = new JLabel("Sum:", JLabel.CENTER); JTextField F1 = new JTextField(5); JTextField F2 = new JTextField(5); JLabel no3 = new JLabel(); public Test() { super("Test"); Container container = getContentPane(); container.setLayout(new FlowLayout()); container.add(no1); container.add(F1); container.add(no2); container.add(F2); container.add(sum); container.add(no3); F1.setText("5"); // set 5 in F1 F2.setText("5"); // set 5 in F2 int n1 = Integer.parseInt((F1.getText())); // 5 int n2 = Integer.parseInt((F2.getText())); // 5 int no4 = n1 + n2; // 10 String s1 = String.valueOf(no4); no3.setText(s1); } public static void main(String[] args) { Test test = new Test(); test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); test.setSize(500, 400); test.setVisible(true); } } ____________________________________________________ ==================================================== ____________________________________________________ package said; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Example extends JFrame implements ActionListener { private JLabel labelQuestion; private JLabel labelWeight; private JTextField fieldWeight; private JButton buttonTellMe; public Example() { super("Water Calculator"); initComponents(); setSize(240, 150); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } private void initComponents() { labelQuestion = new JLabel("Sa uje duhet te pi?"); labelWeight = new JLabel("Pesha ime ne (kg):"); fieldWeight = new JTextField(5); buttonTellMe = new JButton("Me trego sa?"); setLayout(new FlowLayout()); add(labelQuestion); add(labelWeight); add(fieldWeight); add(buttonTellMe); buttonTellMe.addActionListener(this); } public void actionPerformed(ActionEvent event) { String message = "Ju duhet te pini %.1f L uje ne dite!"; float weight = Float.parseFloat(fieldWeight.getText()); float waterAmount = calculateWaterAmount(weight); message = String.format(message, waterAmount); JOptionPane.showMessageDialog(this, message); } private float calculateWaterAmount(float weight) { return (weight / 10f) * 0.4f; } public static void main(String[] args) { new Example().setVisible(true); } } ____________________________________________________ ==================================================== ____________________________________________________ import java.awt.BorderLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextField; public class Calculator implements ActionListener { private static JTextField inputBox; Calculator(){} public static void main(String[] args) { createWindow(); } private static void createWindow() { JFrame frame = new JFrame("Calculator"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); createUI(frame); frame.setSize(200, 200); frame.setLocationRelativeTo(null); frame.setVisible(true); } private static void createUI(JFrame frame) { JPanel panel = new JPanel(); Calculator calculator = new Calculator(); GridBagLayout layout = new GridBagLayout(); GridBagConstraints gbc = new GridBagConstraints(); panel.setLayout(layout); inputBox = new JTextField(10); inputBox.setEditable(false); JButton button0 = new JButton("0");JButton button1 = new JButton("1"); JButton button2 = new JButton("2");JButton button3 = new JButton("3"); JButton button4 = new JButton("4");JButton button5 = new JButton("5"); JButton button6 = new JButton("6");JButton button7 = new JButton("7"); JButton button8 = new JButton("8");JButton button9 = new JButton("9"); JButton buttonPlus = new JButton("+");JButton buttonMinus = new JButton("-"); JButton buttonDivide = new JButton("/");JButton buttonMultiply = new JButton("x"); JButton buttonClear = new JButton("C");JButton buttonDot = new JButton("."); JButton buttonEquals = new JButton("="); button1.addActionListener(calculator);button2.addActionListener(calculator); button3.addActionListener(calculator);button4.addActionListener(calculator); button5.addActionListener(calculator);button6.addActionListener(calculator); button7.addActionListener(calculator);button8.addActionListener(calculator); button9.addActionListener(calculator);button0.addActionListener(calculator); buttonPlus.addActionListener(calculator);buttonMinus.addActionListener(calculator); buttonDivide.addActionListener(calculator);buttonMultiply.addActionListener(calculator); buttonClear.addActionListener(calculator);buttonDot.addActionListener(calculator); buttonEquals.addActionListener(calculator); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.gridx = 0; gbc.gridy = 0; panel.add(button1, gbc); gbc.gridx = 1; gbc.gridy = 0; panel.add(button2, gbc); gbc.gridx = 2; gbc.gridy = 0; panel.add(button3, gbc); gbc.gridx = 3; gbc.gridy = 0; panel.add(buttonPlus, gbc); gbc.gridx = 0; gbc.gridy = 1; panel.add(button4, gbc); gbc.gridx = 1; gbc.gridy = 1; panel.add(button5, gbc); gbc.gridx = 2; gbc.gridy = 1; panel.add(button6, gbc); gbc.gridx = 3; gbc.gridy = 1; panel.add(buttonMinus, gbc); gbc.gridx = 0; gbc.gridy = 2; panel.add(button7, gbc); gbc.gridx = 1; gbc.gridy = 2; panel.add(button8, gbc); gbc.gridx = 2; gbc.gridy = 2; panel.add(button9, gbc); gbc.gridx = 3; gbc.gridy = 2; panel.add(buttonDivide, gbc); gbc.gridx = 0; gbc.gridy = 3; panel.add(buttonDot, gbc); gbc.gridx = 1; gbc.gridy = 3; panel.add(button0, gbc); gbc.gridx = 2; gbc.gridy = 3; panel.add(buttonClear, gbc); gbc.gridx = 3; gbc.gridy = 3; panel.add(buttonMultiply, gbc); gbc.gridwidth = 3; gbc.gridx = 0; gbc.gridy = 4; panel.add(inputBox, gbc); gbc.gridx = 3; gbc.gridy = 4; panel.add(buttonEquals, gbc); frame.getContentPane().add(panel, BorderLayout.CENTER); } public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if (command.charAt(0) == 'C') { inputBox.setText(""); }else if (command.charAt(0) == '=') { inputBox.setText(evaluate(inputBox.getText())); }else { inputBox.setText(inputBox.getText() + command); } } public static String evaluate(String expression) { char[] arr = expression.toCharArray(); String operand1 = "";String operand2 = "";String operator = ""; double result = 0; for (int i = 0; i < arr.length; i++) { if (arr[i] >= '0' && arr[i] <= '9' || arr[i] == '.') { if(operator.isEmpty()){ operand1 += arr[i]; }else{ operand2 += arr[i]; } } if(arr[i] == '+' || arr[i] == '-' || arr[i] == '/' || arr[i] == '*') { operator += arr[i]; } } if (operator.equals("+")) result = (Double.parseDouble(operand1) + Double.parseDouble(operand2)); else if (operator.equals("-")) result = (Double.parseDouble(operand1) - Double.parseDouble(operand2)); else if (operator.equals("/")) result = (Double.parseDouble(operand1) / Double.parseDouble(operand2)); else result = (Double.parseDouble(operand1) * Double.parseDouble(operand2)); return operand1 + operator + operand2 + "=" +result; } } ____________________________________________________ ==================================================== ____________________________________________________ // Presents a GUI to verify credit card numbers. // Final version with event handling. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class CreditCardGUI2 implements ActionListener { public static void main(String[] args) { CreditCardGUI2 gui = new CreditCardGUI2(); } // fields private JFrame frame; private JTextField numberField; private JLabel validLabel; private JButton verifyButton; // creates components, does layout, shows window onscreen public CreditCardGUI2() { numberField = new JTextField(16); validLabel = new JLabel("not yet verified"); verifyButton = new JButton("Verify CC Number"); // event listeners verifyButton.addActionListener(this); frame = new JFrame("Credit card number verifier"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(new Dimension(350, 100)); frame.setLayout(new FlowLayout()); frame.add(numberField); frame.add(verifyButton); frame.add(validLabel); frame.setVisible(true); } // Returns whether the given string is a valid Visa // card number according to the Luhn checksum algorithm. public boolean isValidCC(String text) { int sum = 0; for (int i = text.length() – 1; i >= 0; i--) { int digit = Integer.parseInt( text.substring(i, i + 1)); if (i % 2 == 0) { // double even digits digit *= 2; } sum += (digit / 10) + (digit % 10); } // valid numbers add up to a multiple of 10 return sum % 10 == 0 && text.startsWith("4"); } // Sets label's text to show whether CC number is valid. public void actionPerformed(ActionEvent event) { String text = numberField.getText(); if (isValidCC(text)) { validLabel.setText("Valid number!"); } else { validLabel.setText("Invalid number."); } } }
//STEP 1. Import required packages import java.sql.*; public class JDBCExample { // JDBC driver name and database URL static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost/STUDENTS"; // Database credentials static final String USER = "username"; static final String PASS = "password"; public static void main(String[] args) { Connection conn = null; Statement stmt = null; try{ //STEP 2: Register JDBC driver Class.forName("com.mysql.jdbc.Driver"); //STEP 3: Open a connection System.out.println("Connecting to a selected database..."); conn = DriverManager.getConnection(DB_URL, USER, PASS); System.out.println("Connected database successfully..."); //STEP 4: Execute a query System.out.println("Creating table in given database..."); stmt = conn.createStatement(); String sql = "CREATE TABLE REGISTRATION " + "(id INTEGER not NULL, " + " first VARCHAR(255), " + " last VARCHAR(255), " + " age INTEGER, " + " PRIMARY KEY ( id ))"; stmt.executeUpdate(sql); System.out.println("Created table in given database..."); }catch(SQLException se){ //Handle errors for JDBC se.printStackTrace(); }catch(Exception e){ //Handle errors for Class.forName e.printStackTrace(); }finally{ //finally block used to close resources try{ if(stmt!=null) conn.close(); }catch(SQLException se){ }// do nothing try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); }//end finally try }//end try System.out.println("Goodbye!"); }//end main }//end JDBCExampleWorking connection
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; public class said { public static void main(String[] args) { // creates three different Connection objects Connection conn1 = null; Connection conn2 = null; Connection conn3 = null; try { // connect way #1 String url1 = "jdbc:mysql://localhost:3306/sakila"; String user = "root"; String password = "rootroot"; conn1 = DriverManager.getConnection(url1, user, password); if (conn1 != null) { System.out.println("Connected to the database test1"); } } catch (SQLException ex) { System.out.println("An error occurred. Maybe user/password is invalid"); ex.printStackTrace(); } } }
Calculator
import java.awt.BorderLayout; import java.awt.Container; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextField; public class Calculator extends JPanel implements ActionListener { private JTextField display = new JTextField("0"); private double result = 0; private String operator = "="; private boolean calculating = true; public Calculator() { setLayout(new BorderLayout()); display.setEditable(false); add(display, "North"); JPanel panel = new JPanel(); panel.setLayout(new GridLayout(4, 4)); String buttonLabels = "789/456*123-0.=+"; for (int i = 0; i < buttonLabels.length(); i++) { JButton b = new JButton(buttonLabels.substring(i, i + 1)); panel.add(b); b.addActionListener(this); } add(panel, "Center"); } public void actionPerformed(ActionEvent evt) { String cmd = evt.getActionCommand(); if ('0' <= cmd.charAt(0) && cmd.charAt(0) <= '9' || cmd.equals(".")) { if (calculating) display.setText(cmd); else display.setText(display.getText() + cmd); calculating = false; } else { if (calculating) { if (cmd.equals("-")) { display.setText(cmd); calculating = false; } else operator = cmd; } else { double x = Double.parseDouble(display.getText()); calculate(x); operator = cmd; calculating = true; } } } private void calculate(double n) { if (operator.equals("+")) result += n; else if (operator.equals("-")) result -= n; else if (operator.equals("*")) result *= n; else if (operator.equals("/")) result /= n; else if (operator.equals("=")) result = n; display.setText("" + result); } public static void main(String[] args) { JFrame.setDefaultLookAndFeelDecorated(true); JFrame frame = new JFrame(); frame.setTitle("Calculator"); frame.setSize(200, 200); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); Container contentPane = frame.getContentPane(); contentPane.add(new Calculator()); frame.show(); } }
Ushtrimi 1:
import java.util.*; class School { String dept; double fees; public School(String dept , double fees) { this.dept = dept; this.fees = fees; } public void printSchoolInfo() { System.out.println("Deptarment: "+dept); System.out.println("Fees: "+fees); } } //file2 class Subject extends School{ int no_of_student; public Subject(String dept , double fees,int no_of_student) { super(dept,fees); this.no_of_student = no_of_student; } public void printSubjectInfo() { super.printSchoolInfo(); System.out.println("No of student enrolled: "+no_of_student); } } //file3 class student_Status extends Subject{ String pass_fail; public student_Status(String dept , double fees,int no_of_student,String pass_fail) { super(dept,fees,no_of_student); this.pass_fail = pass_fail; } public void printstudent_StatusInfo() { super.printSubjectInfo(); System.out.println("Pass/Fail: "+pass_fail); } } //Programi kryesor public class Main { public static void main(String args[]) { student_Status obj=new student_Status("Computer",1025.5,35,"Pass"); obj.printstudent_StatusInfo(); } }
Code a short JAVA program that demonstrates Inheritance.
HINT:
· To demonstrate true OOP inheritance, your code must include a super (parent) class and a sub class (derived class)
· As an example, class Student could be a super class while class GraduateStudent is a sub class that inherits from Student class.
· In your subclass (i.e. GraduateStudent), you must include the JAVA inheritance keyword that shows that a class inherits from another.
Program: import java.io.*; // Parent class class Student { String name; String rollnumber; //Constructor public Student(String na, String rno) { name = na; rollnumber=rno; System.out.println("Parent class"); } // Get the name public String getName() { return name; } // Get the roll number public String getrollno() { return rollnumber; } } //Derived class class GraduateStudent extends Student { private String grade; // Constructor of derived class public GraduateStudent(String na, String rno, String grad) { super(na,rno); grade=grad; System.out.println("Derived class"); } // Method to get grade public String getGrade() { return grade; } // Method to display the details public void details() { System.out.println(super.getName()+super.getrollno()+" and "+getGrade()); } } // Test class public class StudentTest { // Main method public static void main(String[] args) { GraduateStudent cobj = new GraduateStudent("Alex " , "10ABC11 ","C"); cobj.details(); } }
// Hangman game import java.util.Scanner; import java.util.Random; class Game { static Scanner input; public static void hangman() { input = new Scanner(System.in); // Stringjet ne array qe mbajne fjalet String[] company = { "impact", "Tata", "Suzuki", "Ducati", "Toyota" }; System.out.println( " Welcome to HANGMAN GAME "); Random obj = new Random(); int Ran_num = obj.nextInt(5); // merr inputin e fjales String word = (company[Ran_num]); word = word.toUpperCase(); // Shfaq _ String word1 = word.replaceAll("[A-Z]", "_ "); // Metoda qe ben play System.out.println("let's play the game"); startGame(word, word1); } public static void startGame(String word, String word1) { // hamendesimet int guess_ = 0; // hamdesimet gabim int wrong = 0; // per cdo hamendesim String guess; // ruan shkronjen e hamedesuar char letter; // ruan shkronjen nese ishte // tashme e hamedesuar boolean guessescontainsguess; String guesses = ""; boolean guessinword; // kushti while while (wrong < 5 && word1.contains("_")) { System.out.println(word1 + "\n"); int temp = 5 - wrong; if (wrong != 0) { // per foton e 1 System.out.println("You have " + temp + " guesses left."); } System.out.print("Your Guess:"); // merr nga tastiera hamendesimin guess = input.nextLine(); // konverton ne shrkonja te medha // per krahasim guess = guess.toUpperCase(); // merr shkronjen e pare // si shkronje e hamedesuar letter = guess.charAt(0); guessescontainsguess = (guesses.indexOf(letter)) != -1; // ruan cdo shkronje // te hamendesuar guesses += letter; // konverton ne shrkonja te medha // per krahasim letter = Character.toUpperCase(letter); System.out.println(); // nese shkronja eshte hamedesuar me pare if (guessescontainsguess == true) { // eshte shkronje e hamedesuar tashme System.out.println("You ALREADY guessed " + letter + ". \n"); } // shkronja e hamendesuar ne fjale guessinword = (word.indexOf(letter)) != -1; // kushti if if (guessinword == true) { // afisho shkronjen System.out.println( letter + " is present in the word."); System.out.print("\n"); // gjeni pozicionet e shkronjave // zëvendësoni vizat me ato // letër në pozicione të vlefshme for (int position = 0; position < word.length(); position++) { // shkronja e supozuar është e barabartë me // shkronja në pozicion në fjalë // dhe word1 më parë nuk ka // kanë atë letër if (word.charAt(position) == letter && word1.charAt(position) != letter) { word1 = word1.replaceAll("_ ", "_"); String word2; word2 = word1.substring(0, position) + letter + word1.substring(position + 1); word2 = word2.replaceAll("_", "_ "); word1 = word2; } } } //nëse if përfundon, përndryshe else if fillon else { // printime // gabim = gabim + 1, pas çdo // përgjigje të gabuar System.out.println( letter + " is not present in the word."); wrong++; } // guess_ = guess_ + 1, pas çdo // përpjekje guess_++; } // while loop perfundon // nëse linjat e shpëtimit mbarojnë if (wrong == 5) { System.out.println( "YOU LOST!, maximum limit of incorrect guesses reached."); } else { // zgjidhur me sukses System.out.print( "The word is: " + word1 + "\n Well Played, you did it!!"); } } public static void main(String[] args) { // LUAJ LOJEN hangman(); } }