Said Dulevic

Msc Said Dulevic

Web Developer & Lecturer

Java – Programim ne Java Shqip (Kursi i plote)

Ushtrime mbi klasat dhe objektet

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);
  }
}

Shume Objekte ne 1 klase

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
  }

Konstruktoret

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

Inheritance (Trashgimia)

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);
  }
}

Notat e nje Studenti

import java.util.Scanner;

public class NotaStudenti
{
    public static void main(String args[])
    {
        int notat[] = new int[6];
        int i;
        float total=0, mes;
        Scanner scanner = new Scanner(System.in);
		
        
        for(i=0; i<6; i++) { 
           System.out.print("Vondos notat e Lendes"+(i+1)+":");
           notat[i] = scanner.nextInt();
           total = total + notat[i];
        }
        scanner.close();
        mes = total/6;
        System.out.print("Nota e Studentit eshte: ");
        if(mes>=80)
        {
            System.out.print("Exelent");
        }
        else if(mes>=60 && mes<80)
        {
           System.out.print(" Shume Mire");
        } 
        else if(mes>=40 && mes<60)
        {
            System.out.print("Mire");
        }
        else
        {
            System.out.print("Keq");
        }
    }
}

Ushtrimi 2: Gjenu numrin e 3te me te madh

    public class nrtretemeimadh{  
    public static int gjejtret(int[] a, int total){  
    int temp;  
    for (int i = 0; i < total; i++)   
            {  
                for (int j = i + 1; j < total; j++)   
                {  
                    if (a[i] > a[j])   
                    {  
                        temp = a[i];  
                        a[i] = a[j];  
                        a[j] = temp;  
                    }  
                }  
            }  
           return a[total-3];  
    }  
    public static void main(String args[]){  
    int a[]={1,2,5,6,3,2};  
    int b[]={44,66,99,77,33,22,55};  
    System.out.println("I treti me i madh: "+gjejtret(a,6));  
    System.out.println("I treti me i madh: "+gjejtret(b,7));  
    }}  

Ushtrimi 3: Mbledhja e 2 matricave

	    public class matrica{  
    public static void main(String args[]){  
    int a[][]={{1,3,4},{2,4,3},{3,4,5}};    
    int b[][]={{1,3,4},{2,4,3},{1,2,4}};    
 
    int c[][]=new int[3][3];   
        
 
    for(int i=0;i<3;i++){    
    for(int j=0;j<3;j++){    
    c[i][j]=a[i][j]+b[i][j];    
    System.out.print(c[i][j]+" ");    
    }    
    System.out.println();   
    }    
    }}  

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);
   }
}

Shuma e dy Numrave

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);
	}

}

Llogaritesi i sasise se ujit qe duhet pire sipas peshes

package said;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
 
/**
 * A Java Swing program that shows how much water you should drink a day.
 * @author www.codejava.net
 */
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);
    }
}

Java Swing Makine Llogaritese

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;
   }    
} 
Leksione plus Ushtrime dhe Shembuj
//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 JDBCExample
Working 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();
  }
}

Shumzimi i dy numrava


import java.util.Scanner;
 
public class Exercise5 {
 
 public static void main(String[] args) {
  Scanner in = new Scanner(System.in);
   
  System.out.print("Vendos numrin e pare: ");
  int num1 = in.nextInt();
   
  System.out.print("Vendos numrin e dyte: ");
  int num2 = in.nextInt();
   
  System.out.println(num1 + " x " + num2 + " = " + num1 * num2);
 }
 
}

Perimetri dhe siperfaqja e rrethit



public class Exercise11 {
 
   private static final double rreze = 7.5;

    public static void main(String[] args) {

        double perimetri = 2 * Math.PI * rreze;
        double sip = Math.PI * rreze * rreze;

        System.out.println("Perimetri eshte = " + perimetri);
        System.out.println("Siperfaqja eshte = " + sip);
    }
}


Mesatarja e semestrit shkollor


import java.util.Scanner;
 
public class Exercise12 {
 
 public static void main(String[] args) {
  Scanner in = new Scanner(System.in);
   
  System.out.print("Vendos noten 1: ");
  int num1 = in.nextInt();
   
  System.out.print("Vendos noten 2: ");
  int num2 = in.nextInt();
   
  System.out.print("Vendos noten 3: ");
  int num3 = in.nextInt();
   
  System.out.print("Vendos noten 4: ");
  int num4 = in.nextInt();
  
  System.out.print("Vendos noten 5: ");
  int num5 = in.nextInt();
   
   
  System.out.println("Mesatarja e 5 notave eshte: " + 
   (num1 + num2 + num3 + num4 + num5) / 5);
 }
}


Ushtrim per numrat cift dhe tek


import java.util.Scanner;

class CheckEvenOdd
{
  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 juaj eshte cift");
     else
        System.out.println("Numri juaj eshte tek");
  }
}

Llogaritja e pageses me keste

  

import java.util.Scanner;
public class JavaExample
{
    public static void main(String args[]) 
    {
        float p, r, t, sinterest;
        Scanner scan = new Scanner(System.in);
        System.out.print("Vendos shumen : ");
        p = scan.nextFloat();
        System.out.print("Vendos perqindjen e interesit: ");
        r = scan.nextFloat();
        System.out.print("Koha e kestit: ");
        t = scan.nextFloat();
        scan.close();
        sinterest = (p * r * t) / 100;
        System.out.print("Interesi qe duhet te paguani: " +sinterest);
    }
}

Shkruani nje Program i cili merr 10 numra dhe i kthen ne te kundertet (reverse)


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] + " ");
    }
}

Java If-Else if - else

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.");
      } 
   }
}

Ditet e javes Switch-Case

class Day {
   public static void main(String[] args) {
      int week = 4;
      String dita;
	        
      switch (week) {
         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);
   }
}

Makine Llogaritese Switch Case

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;
        }       
    }
}

Krijimi i klases student dhe hedhja e te dhenave

class PrintStudentDetailsUsingClasses
{
    public static void main(String s[])
    {
        Student students[] = new Student[5];
    
        students[0] = new Student();
        students[0].emri = "Said";
        students[0].pike = 45;
        students[0].seksioni = 'A';
    
        students[1] = new Student();
        students[1].emri = "Smart";
        students[1].pike = 78;
        students[1].seksioni = 'B';
    
        students[2] = new Student();
        students[2].emri = "Ramesh";
        students[2].pike = 83;
        students[2].seksioni = 'A';
    
        students[3] = new Student();
        students[3].emri = "Albi";
        students[3].pike = 77;
        students[3].seksioni = 'A';
    
        students[4] = new Student();
        students[4].emri = "center";
        students[4].pike = 93;
        students[4].seksioni = 'B';
    
    
        for(int i = 0; i < students.length; i++)
        {
            System.out.println( students[i].emri + " ne seksionin " + students[i].seksioni + " ka marre " + students[i].pike + " pike." );
        }
    }

}

class Student
{
    String emri;
    int pike;
    char seksioni;
    String adresa;
    String celular; }

Krijimi i klases Libri

public class Book 
{
	// instance variable
	String title;
	String author;
	String genre;
	double price;

	public static void main(String[] args) 
	{
		// creating first object of Book
		Book book1 = new Book();
		// assigning instance variable values
		book1.title = "Java Complete Reference";
		book1.author = "Herbert Schield";
		book1.genre = "Computer Programming";
		book1.price = 300.0;

		// creating second object of Book
		Book book2 = new Book();
		// assigning instance variable values
		book2.title = "One, Two, Three, Infinity";
		book2.author = "George Gamow";
		book2.genre = "Science";
		book2.price = 600.0;

		System.out.println("I have two books. Which are");
		System.out.println(book1.title + " written by: " + book1.author	+ " and the price is :" + book1.price);
		System.out.println("And");
		System.out.println(book2.title + " written by: " + book2.author	+ " and the price is :" + book2.price);

	}
}

Ushtrim (MyInteger) Me metoda


public class NewMyInteger {
    public static void main(String[] args) {
        MyInteger n1 = new MyInteger(5);
        System.out.println("n1 is even? " + n1.isEven());
        System.out.println("n1 is prime? " + n1.isPrime());
        System.out.println("15 is prime? " + MyInteger.isPrime(15));
        char[] chars = {'3', '5', '3', '9'};
        System.out.println(MyInteger.parseInt(chars));
        String s = "3539";
        System.out.println(MyInteger.parseInt(s));
        MyInteger n2 = new MyInteger(24);
        System.out.println("n2 is odd? " + n2.isOdd());
        System.out.println("45 is odd? " + MyInteger.isOdd(45));
        System.out.println("n1 is equal to n2? " + n1.equals(n2));
        System.out.println("n1 is equal to 5? " + n1.equals(5));
    }
}
class MyInteger {
    int value;
    MyInteger(int newValue) {
        value = newValue;
    }
    public int getValue() {
        return value;
    }
    public static boolean isEven(int n) {
        return (n % 2 == 0);
    }
    public static boolean isOdd(int n) {
        return !isEven(n);
    }
    public static boolean isPrime(int n) {
        for (int f = 2; f < n / 2; f++) {
            if (n % f == 0) {
                return false;
            }
        }
        return true;
    }
    public static boolean isEven(MyInteger n) {
        return n.isEven();
    }
    public static boolean isOdd(MyInteger n) {
        return n.isOdd();
    }
    public static boolean isPrime(MyInteger n) {
        return n.isPrime();
    }
    public boolean isEven() {
        return isEven(value);
    }
    public boolean isOdd() {
        return isOdd(value);
    }
    public boolean isPrime() {
        return isPrime(value);
    }
    public boolean equals(int n) {
        return (value == n);
    }
    public boolean equals(MyInteger n) {
        return equals(n.getValue());
    }
    public static int parseInt(String s) {
        return Integer.parseInt(s);
    }
    public static int parseInt(char[] s) {
        return parseInt(new String(s));
    }
}

Program per klasat dhe subclass

public class Exercise_11_02 {
	// Main method
	public static void main(String[] args) {
		// Create a Person, Student, Employee, Faculty, and Staff objects
		Person person = new Person("John", "12 Bell street", 
			"3473339999", "john12@aol.com");

		Student student = new Student("Mary", "100 Town Ave", "5149993333", 
			"mary100@aol.com", Student.FRESHMAN);

		Employee employee = new Employee("Mike", "34 West street", "6189999999",
			"mike80@aol.com", 910, 60000);

		Faculty faculty = new Faculty("Sue", "28 Well street", "4133333333",
			"sue28@aol.com", 101, 50000, "4pm to 6pm", "Professor");

		Staff staff = new Staff("Tom", "90 Country road", "2030000000",
			"tomcat@aol.com", 12, 65000, "Executive Assistant");

		// Invoke toString of Person, Student, Employee, Faculty and Staff
		System.out.println(person.toString());
		System.out.println(student.toString());
		System.out.println(employee.toString());
		System.out.println(faculty.toString());
		System.out.println(staff.toString());
	}
}

Shkarko KETU

Write a program to print the area of two rectangles having sides (4,5) and (5,8) respectively by creating a class named 'Rectangle' with a method named 'Area' which returns the area and length and breadth passed as parameters to its constructor.

class Rectangle{
  int length;
  int breadth;
  public Rectangle(int l, int b){
    length = l;
    breadth = b;
  }
  public int getArea(){
    return length*breadth;
  }
  public int getPerimeter(){
    return 2*(length+breadth);
  }
}

class Ans{
  public static void main(String[] args){
    Rectangle a = new Rectangle(4,5);
    Rectangle b = new Rectangle(5,8);
    System.out.println("Area : "+a.getArea()+" Perimeter is "+a.getPerimeter());
    System.out.println("Area : "+b.getArea()+" Perimeter is "+b.getPerimeter());
  }
}		

What will be the output of this program?

class A
{
    static int i;
 
    static
    {
        System.out.println(1);
 
        i = 100;
    }
}
 
public class StaticInitializationBlock
{
    static
    {
        System.out.println(2);
    }
 
    public static void main(String[] args)
    {
        System.out.println(3);
 
        System.out.println(A.i);
    }
}

Lab 5 question

public class Alien
{
   protected int eyeNum;
   protected int armNum;
   protected String skinColor;
   protected String raceAlien;

   public Alien(int eye, int arm, String skin, String race)
   {
   eyeNum = eye;
   armNum = arm;
   skinColor = skin;
   raceAlien = race;
   }

public void display()
{
   System.out.println("The " + raceAlien + " has " + eyeNum + 
   " number of eyes and " + armNum + " number of arms " + 
   skinColor + " colour of skin.");
}
}

martianclass

public class Martian extends Alien 
{
   public Martian(int eye, int arm, String skin, String race)
  {
   super(2, 3, "red", "Martian");
  }
}
   
CreateAliens class

   public class CreateAliens
{
   public static void main(String[] args)
   {
   Martian createMartian = new Martian();
   createMartian.display();
   }
}
 

Klasa ATM

public class ATM 
{
   private boolean userAuthenticated; // whether user is authenticated
   private int currentAccountNumber; // current user's account number
   private Screen screen; // ATM's screen
   private Keypad keypad; // ATM's keypad
   private CashDispenser cashDispenser; // ATM's cash dispenser
   private DepositSlot depositSlot; // ATM's deposit slot
   private BankDatabase bankDatabase; // account information database

   // constants corresponding to main menu options
   private static final int BALANCE_INQUIRY = 1;
   private static final int WITHDRAWAL = 2;
   private static final int DEPOSIT = 3;
   private static final int EXIT = 4;

   // no-argument ATM constructor initializes instance variables
   public ATM() 
   {
      userAuthenticated = false; // user is not authenticated to start
      currentAccountNumber = 0; // no current account number to start
      screen = new Screen(); // create screen
      keypad = new Keypad(); // create keypad 
      cashDispenser = new CashDispenser(); // create cash dispenser
      depositSlot = new DepositSlot(); // create deposit slot
      bankDatabase = new BankDatabase(); // create acct info database
   } // end no-argument ATM constructor

   // start ATM 
   public void run()
   {
      // welcome and authenticate user; perform transactions
      while ( true )
      {
         // loop while user is not yet authenticated
         while ( !userAuthenticated ) 
         {
            screen.displayMessageLine( "\nWelcome!" );       
            authenticateUser(); // authenticate user
         } // end while
         
         performTransactions(); // user is now authenticated 
         userAuthenticated = false; // reset before next ATM session
         currentAccountNumber = 0; // reset before next ATM session 
         screen.displayMessageLine( "\nThank you! Goodbye!" );
      } // end while   
   } // end method run

   // attempts to authenticate user against database
   private void authenticateUser() 
   {
      screen.displayMessage( "\nPlease enter your account number: " );
      int accountNumber = keypad.getInput(); // input account number
      screen.displayMessage( "\nEnter your PIN: " ); // prompt for PIN
      int pin = keypad.getInput(); // input PIN
      
      // set userAuthenticated to boolean value returned by database
      userAuthenticated = 
         bankDatabase.authenticateUser( accountNumber, pin );
      
      // check whether authentication succeeded
      if ( userAuthenticated )
      {
         currentAccountNumber = accountNumber; // save user's account #
      } // end if
      else
         screen.displayMessageLine( 
             "Invalid account number or PIN. Please try again." );
   } // end method authenticateUser

   // display the main menu and perform transactions
   private void performTransactions() 
   {
      // local variable to store transaction currently being processed
      Transaction currentTransaction = null;
      
      boolean userExited = false; // user has not chosen to exit

      // loop while user has not chosen option to exit system
      while ( !userExited )
      {     
         // show main menu and get user selection
         int mainMenuSelection = displayMainMenu();

         // decide how to proceed based on user's menu selection
         switch ( mainMenuSelection )
         {
            // user chose to perform one of three transaction types
            case BALANCE_INQUIRY: 
            case WITHDRAWAL: 
            case DEPOSIT:

               // initialize as new object of chosen type
               currentTransaction = 
                  createTransaction( mainMenuSelection );

               currentTransaction.execute(); // execute transaction
               break; 
            case EXIT: // user chose to terminate session
               screen.displayMessageLine( "\nExiting the system..." );
               userExited = true; // this ATM session should end
               break;
            default: // user did not enter an integer from 1-4
               screen.displayMessageLine( 
                  "\nYou did not enter a valid selection. Try again." );
               break;
         } // end switch
      } // end while
   } // end method performTransactions
   
   // display the main menu and return an input selection
   private int displayMainMenu()
   {
      screen.displayMessageLine( "\nMain menu:" );
      screen.displayMessageLine( "1 - View my balance" );
      screen.displayMessageLine( "2 - Withdraw cash" );
      screen.displayMessageLine( "3 - Deposit funds" );
      screen.displayMessageLine( "4 - Exit\n" );
      screen.displayMessage( "Enter a choice: " );
      return keypad.getInput(); // return user's selection
   } // end method displayMainMenu
         
   // return object of specified Transaction subclass
   private Transaction createTransaction( int type )
   {
      Transaction temp = null; // temporary Transaction variable
      
      // determine which type of Transaction to create     
      switch ( type )
      {
         case BALANCE_INQUIRY: // create new BalanceInquiry transaction
            temp = new BalanceInquiry( 
               currentAccountNumber, screen, bankDatabase );
            break;
         case WITHDRAWAL: // create new Withdrawal transaction
            temp = new Withdrawal( currentAccountNumber, screen, 
               bankDatabase, keypad, cashDispenser );
            break; 
         case DEPOSIT: // create new Deposit transaction
            temp = new Deposit( currentAccountNumber, screen, 
               bankDatabase, keypad, depositSlot );
            break;
      } // end switch

      return temp; // return the newly created object
   } // end method createTransaction
} // end class ATM

Klasa Screen

public class Screen
{
   // displays a message without a carriage return
   public void displayMessage( String message ) 
   {
      System.out.print( message ); 
   } // end method displayMessage

   // display a message with a carriage return
   public void displayMessageLine( String message ) 
   {
      System.out.println( message );   
   } // end method displayMessageLine

   // display a dollar amount
   public void displayDollarAmount( double amount )
   {
      System.out.printf( "$%,.2f", amount );   
   } // end method displayDollarAmount 
} // end class Screen

Klasa Keypad

import java.util.Scanner; // program uses Scanner to obtain user input

public class Keypad
{
   private Scanner input; // reads data from the command line
                         
   // no-argument constructor initializes the Scanner
   public Keypad()
   {
      input = new Scanner( System.in );    
   } // end no-argument Keypad constructor

   // return an integer value entered by user 
   public int getInput()
   {
      return input.nextInt(); // we assume that user enters an integer  
   } // end method getInput
} // end class Keypad  

CashDispenser

 
public class CashDispenser 
{
   // the default initial number of bills in the cash dispenser
   private final static int INITIAL_COUNT = 500;
   private int count; // number of $20 bills remaining
   
   // no-argument CashDispenser constructor initializes count to default
   public CashDispenser()
   {
      count = INITIAL_COUNT; // set count attribute to default
   } // end CashDispenser constructor

   // simulates dispensing of specified amount of cash
   public void dispenseCash( int amount )
   {
      int billsRequired = amount / 20; // number of $20 bills required
      count -= billsRequired; // update the count of bills
   } // end method dispenseCash

   // indicates whether cash dispenser can dispense desired amount
   public boolean isSufficientCashAvailable( int amount )
   {
      int billsRequired = amount / 20; // number of $20 bills required

      if ( count >= billsRequired  )
         return true; // enough bills available
      else 
         return false; // not enough bills available
   } // end method isSufficientCashAvailable
} // end class CashDispenser

DepositSlot

public class DepositSlot 
{
   // indicates whether envelope was received (always returns true, 
   // because this is only a software simulation of a real deposit slot)
   public boolean isEnvelopeReceived()
   {
      return true; // deposit envelope was received
   } // end method isEnvelopeReceived
} // end class DepositSlot

Bank Database

public class BankDatabase
{
   private Account accounts[]; // array of Accounts
   
   // no-argument BankDatabase constructor initializes accounts
   public BankDatabase()
   {
      accounts = new Account[ 2 ]; // just 2 accounts for testing
      accounts[ 0 ] = new Account( 12345, 54321, 1000.0, 1200.0 );
      accounts[ 1 ] = new Account( 98765, 56789, 200.0, 200.0 );  
   } // end no-argument BankDatabase constructor
   
   // retrieve Account object containing specified account number
   private Account getAccount( int accountNumber )
   {
      // loop through accounts searching for matching account number
      for ( Account currentAccount : accounts )
      {
         // return current account if match found
         if ( currentAccount.getAccountNumber() == accountNumber )
            return currentAccount;
      } // end for

      return null; // if no matching account was found, return null
   } // end method getAccount

   // determine whether user-specified account number and PIN match
   // those of an account in the database
   public boolean authenticateUser( int userAccountNumber, int userPIN )
   {
      // attempt to retrieve the account with the account number
      Account userAccount = getAccount( userAccountNumber );

      // if account exists, return result of Account method validatePIN
      if ( userAccount != null )
         return userAccount.validatePIN( userPIN );
      else
         return false; // account number not found, so return false
   } // end method authenticateUser

   // return available balance of Account with specified account number
   public double getAvailableBalance( int userAccountNumber )
   {
      return getAccount( userAccountNumber ).getAvailableBalance();
   } // end method getAvailableBalance

   // return total balance of Account with specified account number
   public double getTotalBalance( int userAccountNumber )
   {
      return getAccount( userAccountNumber ).getTotalBalance();
   } // end method getTotalBalance

   // credit an amount to Account with specified account number
   public void credit( int userAccountNumber, double amount )
   {
      getAccount( userAccountNumber ).credit( amount );
   } // end method credit

   // debit an amount from of Account with specified account number
   public void debit( int userAccountNumber, double amount )
   {
      getAccount( userAccountNumber ).debit( amount );
   } // end method debit
} // end class BankDatabase
More codes are here : HERE

Ndërtoni një klasë në Java të quajtur Studenti, e cila përmban tre variabla: emrin e studentit, lenden dhe noten qe ai ka marrre ne provim: Krijoni:  konstruktorin e klasës Studenti  metodat get() dhe set(), për të implementuar enkapsulimin  një metodë toString( ), e cila shfaq të dhënat e studentit  një klasë TestStudenti, në të cilën duhet të krijoni dy objekte std1 (test, Gjuhe Programimi, 9) dhe std2 (test2, Baze te dhenash, 10). Më pas thërrisni metodën afisho( ) për të shfaqur të dhënat përkatese të objekteve. Te dhenat e userave merren me scanner dhe per te krijuar objektin per studentin e dyte thjesht shtoni std2 dhe perseritni hapat tek TestStudenti

package said;

public class Student {

    private int id;
    private String emri;
    private int lenda1;
    private int lenda2;
    private int lenda3;

    public void setEmri(String s) {
        emri = s;
    }

    public String getEmri() {
        return emri;
    }

    public void setid(int r) {
        if (r > 0) {
            id = r;
        } else {
            id = 1;
        }
    }

    public int getid() {
        return id;
    }

    public void setLenda1(int m) {
        if (m >= 4 && m <= 10) {
            lenda1 = m;
        } else {
            lenda1 = 0;
        }
    }

    public int getLenda1() {
        return lenda1;
    }

    public void setLenda2(int m) {
        if ((m >= 4) && (m <= 10)) {
            lenda2 = m;
        } else {
            lenda2 = 0;
        }
    }

    public int getLenda2() {
        return lenda2;
    }

    public void setLenda3(int m) {
        if ((m >= 4) && m <= 10) {
            lenda3 = m;
        } else {
            lenda3 = 0;
        }
    }

    public int getLenda3() {
        return lenda3;
    }

    public double getmesatarja() {
        return (lenda1+ lenda2 + lenda3) / 3.0;
    }

    public void afisho() {
        System.out.println("Id e Studentit: " + id);
        System.out.println("Emri: " + emri);
        System.out.println("Nota ne lenden e pare: " + lenda1);
        System.out.println("Nota ne lenden e dyte: " + lenda2);
        System.out.println("Nota ne lenden e trete: " + lenda3);
        System.out.println("Mesatarja: " + getmesatarja());
    }
}




Krijojme tashme klasen TestStudent

package said;

import java.util.Scanner;

public class TestStudent {

    public static void main(String[] args) {
        Student std1 = new Student();
        Scanner scanner = new Scanner(System.in);
        System.out.print("Vendos Emrin: ");
        String emri = scanner.nextLine();
        std1.setEmri(emri);
        System.out.print("Vendos ID: ");
        int id = scanner.nextInt();
        std1.setid(id);
        System.out.print("Vendos noten per lenden 1: ");
        int lenda1 = scanner.nextInt();
        std1.setLenda1(lenda1);
        System.out.print("Vendos noten per lenden 2: ");
        int nota2 = scanner.nextInt();
        std1.setLenda2(nota2);
        System.out.print("Vendos noten per lenden 3: ");
        int nota3 = scanner.nextInt();
        std1.setLenda3(nota3);
        System.out.println();
        System.out.println("Afishimi i te dhenave me metoden afisho()  =");
        std1.afisho();
        System.out.println();

    }
}

animationss

error: Alert: Ups materiali eshte i bllokuar!!
Need Help? Chat with me