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

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

error: Materiali eshte i bllokuar, e mira eshte ta shkruani vet! Suksese!
www.mersinportal.net | www.idealminer.com | www.thefabric.com.tr