Java

Емкаа

the worst thing about prison was the dementors.
Член од
14 мај 2008
Мислења
4.910
Поени од реакции
12.395
Еве ја класата каде што се креираат и додаваат бродовите

Код:
public class AddShip implements FactoryAdd {
Ship ship;
  
  
    @Override
    public Ship add(Pozicija p, int s, String type, Grid board) {
  
      
        boolean isHorizontal = (s == 0);
      

        if(type.equals("Battleship"))
        {

            try
            {
              
                if(!board.niza.contains(ship))
              
                {
                    ship=new Battleship(board,p,isHorizontal);
                System.out.println("DODADOV Battle na pozicija "+board.niza.indexOf(ship));
                board.niza.add(ship);
              
                }
              
            }
          
            catch (PositionOccupiedException Exception)
            {
                System.out.println(String.format("Cannot place %s battleship here, position is occupied \n", (isHorizontal? "horizontal" : "vertical")));
            }
          
            catch (PositionExceedsBoardException Exception)
            {
                System.out.println(String.format("Cannot place %s battleship here, ship will not fit on grid \n", (isHorizontal? "horizontal" : "vertical")));
            }
        }
      
        if(type.equals("Minesweeper"))
        {
            try
            {
                if(!board.niza.contains(ship)){
                ship=new Minesweeper(board, p, isHorizontal);
                board.niza.add(ship);
                System.out.println("DODADOV Mine na pozicija "+board.niza.indexOf(ship));
              
                }
              
                }
          
            catch (PositionOccupiedException Exception)
            {
                System.out.println(String.format("Cannot place %s Minesweeper here, position is occupied \n", (isHorizontal? "horizontal" : "vertical")));
            }
          
            catch (PositionExceedsBoardException Exception)
            {
                System.out.println(String.format("Cannot place %s Minesweeper here, ship will not fit on grid \n", (isHorizontal? "horizontal" : "vertical")));
            }
          
        }
         if(type.equals("Air"))
        {
            try
            {
                if(!board.niza.contains(ship)){  
            ship=new AircraftCarrier(board,p, isHorizontal);
            board.niza.add(ship);
            System.out.println("DODADOV Air na pozicija " +board.niza.indexOf(ship));
          
                }
           
             }
          
            catch (PositionOccupiedException Exception)
            {
                System.out.println(String.format("Cannot place %s Aircraft Carrier here, position is occupied \n", (isHorizontal? "horizontal" : "vertical")));
            }
          
            catch (PositionExceedsBoardException Exception)
            {
                System.out.println(String.format("Cannot place %s Aircraft Carrier here, ship will not fit on grid \n", (isHorizontal? "horizontal" : "vertical")));
            }
          
        }
      
         if(type.equals("Submarine"))
        {
          
            try{
              
                if(!board.niza.contains(ship)){
                ship=new Submarine(board,p, isHorizontal);  
                board.niza.add(ship);
                System.out.println("DODADOV Sub na pozicija "+board.niza.indexOf(ship));
              
                }
            }
          
            catch (PositionOccupiedException Exception)
            {
                System.out.println(String.format("Cannot place %s submarine here, position is occupied \n", (isHorizontal? "horizontal" : "vertical")));
            }
          
            catch (PositionExceedsBoardException Exception)
            {
                System.out.println(String.format("Cannot place %s submarine here, ship will not fit on grid \n", (isHorizontal? "horizontal" : "vertical")));
            }
          
        }
      
         if(type.equals("Destroyer"))
        {
            try{
              
                if(!board.niza.contains(ship)){
                 ship= new Destroyer(board,p, isHorizontal);
                 board.niza.add(ship);
                 System.out.println("DODADOV Des na pozicija "+board.niza.indexOf(ship));
          
            }
            }
            catch (PositionOccupiedException Exception)
            {
                System.out.println(String.format("Cannot place %s destroyer here, position is occupied \n", (isHorizontal? "horizontal" : "vertical")));
            }
          
            catch (PositionExceedsBoardException Exception)
            {
                System.out.println(String.format("Cannot place %s destroyer here, ship will not fit on grid \n", (isHorizontal? "horizontal" : "vertical")));
            }
          
        }
      
  
      
         return ship;
      
}




}

Тука е методата од класата Grid кај шо се повикува методата addShip

Код:
public boolean addShip(Pozicija p,int s,String type)
  
    {
        AddShip factory=new AddShip();
        ship=factory.add(p, s, type, this);

        if(niza.size()==5)
        {
            allShipsPlaced=true;
        }
      
        if(checkIsShipPlaced(type))
        return true;
      
        return false;
    }

Ми враќа -1 за Battleship.
 
Член од
28 август 2013
Мислења
3.919
Поени од реакции
11.593
Еве ја класата каде што се креираат и додаваат бродовите

Код:
public class AddShip implements FactoryAdd {
Ship ship;


    @Override
    public Ship add(Pozicija p, int s, String type, Grid board) {

    
        boolean isHorizontal = (s == 0);
    

        if(type.equals("Battleship"))
        {

            try
            {
            
                if(!board.niza.contains(ship))
            
                {
                    ship=new Battleship(board,p,isHorizontal);
                System.out.println("DODADOV Battle na pozicija "+board.niza.indexOf(ship));
                board.niza.add(ship);
            
                }
            
            }
        
            catch (PositionOccupiedException Exception)
            {
                System.out.println(String.format("Cannot place %s battleship here, position is occupied \n", (isHorizontal? "horizontal" : "vertical")));
            }
        
            catch (PositionExceedsBoardException Exception)
            {
                System.out.println(String.format("Cannot place %s battleship here, ship will not fit on grid \n", (isHorizontal? "horizontal" : "vertical")));
            }
        }
    
        if(type.equals("Minesweeper"))
        {
            try
            {
                if(!board.niza.contains(ship)){
                ship=new Minesweeper(board, p, isHorizontal);
                board.niza.add(ship);
                System.out.println("DODADOV Mine na pozicija "+board.niza.indexOf(ship));
            
                }
            
                }
        
            catch (PositionOccupiedException Exception)
            {
                System.out.println(String.format("Cannot place %s Minesweeper here, position is occupied \n", (isHorizontal? "horizontal" : "vertical")));
            }
        
            catch (PositionExceedsBoardException Exception)
            {
                System.out.println(String.format("Cannot place %s Minesweeper here, ship will not fit on grid \n", (isHorizontal? "horizontal" : "vertical")));
            }
        
        }
         if(type.equals("Air"))
        {
            try
            {
                if(!board.niza.contains(ship)){
            ship=new AircraftCarrier(board,p, isHorizontal);
            board.niza.add(ship);
            System.out.println("DODADOV Air na pozicija " +board.niza.indexOf(ship));
        
                }
         
             }
        
            catch (PositionOccupiedException Exception)
            {
                System.out.println(String.format("Cannot place %s Aircraft Carrier here, position is occupied \n", (isHorizontal? "horizontal" : "vertical")));
            }
        
            catch (PositionExceedsBoardException Exception)
            {
                System.out.println(String.format("Cannot place %s Aircraft Carrier here, ship will not fit on grid \n", (isHorizontal? "horizontal" : "vertical")));
            }
        
        }
    
         if(type.equals("Submarine"))
        {
        
            try{
            
                if(!board.niza.contains(ship)){
                ship=new Submarine(board,p, isHorizontal);
                board.niza.add(ship);
                System.out.println("DODADOV Sub na pozicija "+board.niza.indexOf(ship));
            
                }
            }
        
            catch (PositionOccupiedException Exception)
            {
                System.out.println(String.format("Cannot place %s submarine here, position is occupied \n", (isHorizontal? "horizontal" : "vertical")));
            }
        
            catch (PositionExceedsBoardException Exception)
            {
                System.out.println(String.format("Cannot place %s submarine here, ship will not fit on grid \n", (isHorizontal? "horizontal" : "vertical")));
            }
        
        }
    
         if(type.equals("Destroyer"))
        {
            try{
            
                if(!board.niza.contains(ship)){
                 ship= new Destroyer(board,p, isHorizontal);
                 board.niza.add(ship);
                 System.out.println("DODADOV Des na pozicija "+board.niza.indexOf(ship));
        
            }
            }
            catch (PositionOccupiedException Exception)
            {
                System.out.println(String.format("Cannot place %s destroyer here, position is occupied \n", (isHorizontal? "horizontal" : "vertical")));
            }
        
            catch (PositionExceedsBoardException Exception)
            {
                System.out.println(String.format("Cannot place %s destroyer here, ship will not fit on grid \n", (isHorizontal? "horizontal" : "vertical")));
            }
        
        }
    

    
         return ship;
    
}




}

Тука е методата од класата Grid кај шо се повикува методата addShip

Код:
public boolean addShip(Pozicija p,int s,String type)

    {
        AddShip factory=new AddShip();
        ship=factory.add(p, s, type, this);

        if(niza.size()==5)
        {
            allShipsPlaced=true;
        }
    
        if(checkIsShipPlaced(type))
        return true;
    
        return false;
    }

Ми враќа -1 за Battleship.
Овде ти е проблемот, прво додади го објектот, па после печати:
Код:
ship=new Battleship(board,p,isHorizontal);
System.out.println("DODADOV Battle na pozicija "+board.niza.indexOf(ship));// Go zemas index-ot pred objektot da bide dodaden, IndexOf() ti vrakja -1 bidejki takov objekt ne postoi
board.niza.add(ship);
 

the_kop

Модератор
Член од
14 јануари 2011
Мислења
10.432
Поени од реакции
13.558
Untitled2.png

Имам проблем со еднаквото. Значи кога ќе кликнам = не ми го пресметува збирот на задачата претходно, туку само го додава знакот во калкулаторот. Барав по нетов неможев да најдам солуција за ова.

Мислења?
 
Член од
28 август 2013
Мислења
3.919
Поени од реакции
11.593
Прегледај го приврзокот 117809

Имам проблем со еднаквото. Значи кога ќе кликнам = не ми го пресметува збирот на задачата претходно, туку само го додава знакот во калкулаторот. Барав по нетов неможев да најдам солуција за ова.

Мислења?
Ke moze da vidime sto kod imas staveno vo handlerot sto go dodavas kako actonlistener?
 

the_kop

Модератор
Член од
14 јануари 2011
Мислења
10.432
Поени од реакции
13.558
Kako sto gledam od kodov imas samo konkatenacija na stringovi i gi prikazuvas vo textbox, ili greska sum?
Во горниот дел од задачата (кој го немам постирано), имам креирано методи, и тоа за броевите од 0 до 9, за +,-,*,\, (сето тоа со JButton) и еден JTextField (за простор во кој ќе влегуваат броевите).

Во последниот дел пак (кој го постирав), е креирано само како +,-*,\, да влегуваат заедно со броевите (пр. 10 * 5). Е сега, уште ми треба начин како еднаквото да ми ги пресметува операциите претходно напишани.
 
Член од
28 август 2013
Мислења
3.919
Поени од реакции
11.593
Во горниот дел од задачата (кој го немам постирано), имам креирано методи, и тоа за броевите од 0 до 9, за +,-,*,\, (сето тоа со JButton) и еден JTextField (за простор во кој ќе влегуваат броевите).

Во последниот дел пак (кој го постирав), е креирано само како +,-*,\, да влегуваат заедно со броевите (пр. 10 * 5). Е сега, уште ми треба начин како еднаквото да ми ги пресметува операциите претходно напишани.
Во тој случај веднаш под:
Код:
JButton button = (JButton)event.getSource();
додај го овој код, ептен школски кодирано е, ама ќе ти заврши работа.
Код:
float result = 0; int number = 0; char operation = '+';
if(button.getText().equals("=")){
     for(int i = 0; i < windowText.length(); i++){
      
       char c = windowText.charAt(i);
      
       if(Character.isDigit(c)){
         number *= 10;
         number += Character.getNumericValue(c);
       }
      
       if(!Character.isDigit(c) || i == windowText.length()-1)
       {
         switch(operation)
         {
           case '+':
             result += number;
             break;
           case '-':
             result -= number;
             break;
           case '*':
             result *= number;
             break;
           case '/':
             result /= number;
             break;
         }
         number = 0;
         operation = c;
       }
     }
}
Во делот каде што го лепиш текстот од копчињата, направи проверка дали е кликнато еднакво, ако е кликнато, после конкатенацијата на текстот на копчето, направи конкатенација со result променливата.
 
S

smiljo

Гостин
Да не ти е помала резолуцијата на сликата?
go srediv problemot :)[DOUBLEPOST=1429000873][/DOUBLEPOST]mozhe nekoj da me upati kako da povrzam mysql so programata,i dali posle toa ako ja stavam programata so celiot folder vnatre vo usb i ja startuvam vo drug kompjuter ke ja imam bazata na podatoci??[DOUBLEPOST=1429041316][/DOUBLEPOST]
Код:
package testdnevnik;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class StartWindow extends JPanel {
 
   JPanel jp = new JPanel();
   JLabel jl = new JLabel();
   JLabel headline = new JLabel();
   JButton viewStudents = new JButton();
   JButton editStudents = new JButton();
   JButton addStudents = new JButton();
   JButton removeStudents = new JButton();
 
   public StartWindow () {
    
     jp.setLayout(new BorderLayout());

      // slika za pozadina
     jl.setIcon(new ImageIcon("img\\bg2.jpg"));
     jl.setPreferredSize(new Dimension(800,600));
     jl.setMaximumSize(new Dimension(800,600));
     jl.setMinimumSize(new Dimension(800,600));
     jl.setSize(800, 600);

   // naslov
     headline.setText("Dnevnik");
     headline.setLocation(200, 30);
     headline.setHorizontalAlignment(JLabel.CENTER);
     headline.setFont(new Font("Serif", Font.BOLD, 60));
     headline.setForeground(Color.ORANGE);
     headline.setSize(300, 50);
     headline.setVisible(true);
    
      // Buttons
     //View Students - Button
     viewStudents.setText("View All Students");
     viewStudents.setSize(200,40);
     viewStudents.setLocation(250 , 200);
     viewStudents.setVisible(true);
    
      // Edit Students - Button
     editStudents.setText("Edit Students");
     editStudents.setSize(200,40);
     editStudents.setLocation(250 , 300);
     editStudents.setVisible(true);
    
      // Add Students - Button
     addStudents.setText("Add New Students");
     addStudents.setSize(200,40);
     addStudents.setLocation(250 ,400);
     addStudents.setVisible(true);
    
      // Remove Students - Button
     removeStudents.setText("Remove Students");
     removeStudents.setSize(200,40);
     removeStudents.setLocation(250 , 500);
     removeStudents.setVisible(true);
   
     // panel
     jp.setPreferredSize(new Dimension(800,600));
     jp.setMaximumSize(new Dimension(800,600));
     jp.setMinimumSize(new Dimension(800,600));
     jp.setSize(800, 600);
   
     jp.add(viewStudents); // add ViewStudents button to the panel
     jp.add(editStudents); // add EditStudents button to the panel
     jp.add(addStudents); // add AddStudents button to the panel
     jp.add(removeStudents); // add RemoveStudents button to the panel
     jp.add(headline); // add headline label to the panel
     jp.add(jl); // add background image to the panel

     add(jp);
   
     validate();
   }
 
   public void checkStudents(int n) {
      int numberOfStudents = n;
         if (numberOfStudents == 0) {
           removeStudents.setEnabled(false);
      }
   }
}
Код:
package testdnevnik;

import javax.swing.JFrame;

public class Dnevnik {
 
   StartWindow startWindow = new StartWindow();
 
   JFrame frame = new JFrame("Dnevnik");
 
   int n = 0;
 
   public Dnevnik() {
  
   startWindow.checkStudents(n);

   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.setSize(800, 600);
   frame.setResizable(false);
   frame.setVisible(true);
   frame.add(startWindow);
 
   }

   public static void main(String[] args) {
      new Dnevnik();
   } 
}
neznam sto e problemot,moze li nekoj da mi kaze sto treba da napravam da nemam bel prostor vo gorniot del??ete go i kodot..
 

Attachments

  • 460,8 KB Прегледи: 22
Последно уредено од модератор:

Makaveli_Gunner

The_Motherfucker*
Член од
4 февруари 2011
Мислења
647
Поени од реакции
274
Едно прашање дали некој ке може да ја реши задача по Јава на испит сум моментално па ако може некаква помош, за да го поминам предметот. Благодарам од напред :D
 

bogev4eboy

Хејтер
Член од
6 март 2011
Мислења
382
Поени од реакции
180
Едно прашање дали некој ке може да ја реши задача по Јава на испит сум моментално па ако може некаква помош, за да го поминам предметот. Благодарам од напред :D
:pos:
 

Amaterasu

123123113
Член од
17 април 2012
Мислења
1.127
Поени од реакции
1.061
Едно прашање дали некој ке може да ја реши задача по Јава на испит сум моментално па ако може некаква помош, за да го поминам предметот. Благодарам од напред :D
Ме интересира, зошто си се запишал на факултет кај што има програмриање ?
 

Have an ice day

Get Free
Член од
26 јануари 2014
Мислења
544
Поени од реакции
1.020
Здраво дечки, задачкава е со хеш, ама по се изгледа hashCode() не ми го зима и покрај тоа што ми е override-нато, т.е си ги сместува елементите во хешот со помош на default-ното, а сакам со моја hashCode() која се наоѓа во класата Lekche, ама не ги внесува. Некој идеа? во прилог цела задача

Код:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package lekovi;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


class SLLNode<E> {
    protected E element;
    protected SLLNode<E> succ;

    public SLLNode(E elem, SLLNode<E> succ) {
        this.element = elem;
        this.succ = succ;
    }

    @Override
    public String toString() {
        return element.toString();
    }
}
class MapEntry<K extends Comparable<K>,E> implements Comparable<K> {

    // Each MapEntry object is a pair consisting of a key (a Comparable
    // object) and a value (an arbitrary object).
    K key;
    E value;

    public MapEntry (K key, E val) {
        this.key = key;
        this.value = val;
    }
   
    public int compareTo (K that) {
    // Compare this map entry to that map entry.
        @SuppressWarnings("unchecked")
        MapEntry<K,E> other = (MapEntry<K,E>) that;
        return this.key.compareTo(other.key);
    }

    public String toString () {
        return "<" + key + "," + value + ">";
    }
}
class CBHT<K extends Comparable<K>, E> {

    // An object of class CBHT is a closed-bucket hash table, containing
    // entries of class MapEntry.
    private SLLNode<MapEntry<K,E>>[] buckets;

    @SuppressWarnings("unchecked")
    public CBHT(int m) {
        // Construct an empty CBHT with m buckets.
        buckets = (SLLNode<MapEntry<K,E>>[]) new SLLNode[m];
    }

    private int hash(K key) {
        // Translate key to an index of the array buckets.
        return Math.abs(key.hashCode()) % buckets.length;
               
    }

    public SLLNode<MapEntry<K,E>> search(K targetKey) {
        // Find which if any node of this CBHT contains an entry whose key is
        // equal
        // to targetKey. Return a link to that node (or null if there is none).
        int b = hash(targetKey);
        for (SLLNode<MapEntry<K,E>> curr = buckets[b]; curr != null; curr = curr.succ) {
            if (targetKey.equals(((MapEntry<K, E>) curr.element).key))
                return curr;
        }
        return null;
    }

    public void insert(K key, E val) {        // Insert the entry <key, val> into this CBHT.
        MapEntry<K, E> newEntry = new MapEntry<K, E>(key, val);
        int b = hash(key);
        for (SLLNode<MapEntry<K,E>> curr = buckets[b]; curr != null; curr = curr.succ) {
            if (key.equals(((MapEntry<K, E>) curr.element).key)) {
                // Make newEntry replace the existing entry ...
                curr.element = newEntry;
                return;
            }
        }
        // Insert newEntry at the front of the 1WLL in bucket b ...
        buckets[b] = new SLLNode<MapEntry<K,E>>(newEntry, buckets[b]);
    }

    public void delete(K key) {
        // Delete the entry (if any) whose key is equal to key from this CBHT.
        int b = hash(key);
        for (SLLNode<MapEntry<K,E>> pred = null, curr = buckets[b]; curr != null; pred = curr, curr = curr.succ) {
            if (key.equals(((MapEntry<K,E>) curr.element).key)) {
                if (pred == null)
                    buckets[b] = curr.succ;
                else
                    pred.succ = curr.succ;
                return;
            }
        }
    }

    public String toString() {
        String temp = "";
        for (int i = 0; i < buckets.length; i++) {
            temp += i + ":";
            for (SLLNode<MapEntry<K,E>> curr = buckets[i]; curr != null; curr = curr.succ) {
                temp += curr.element.toString() + " ";
            }
            temp += "\n";
        }
        return temp;
    }

}



class Lekche{
   
    public String ime;
    public int pozitivnaLista;
    public int cena;
    public int kolicina;
   
   
    public Lekche(String ime, int pozitivnaLista, int cena, int kolicina)
    {
        this.ime = ime;
        this.pozitivnaLista = pozitivnaLista;
        this.cena = cena;
        this.kolicina = kolicina;
    }
   
    @Override
    public int hashCode()
    {
  
        int hash =0;
      for(int i=0;i<ime.length();i++)
        hash += 7 * 31 + ime.charAt(i);
  
      return hash;
    }
   
    public boolean equals(Object obj)
    {
        Lekche lek = (Lekche)obj;
       
        return ime.equals(lek.ime);
       
    }
   
    public void presmetaj(int kolic)
    {
       if(kolic<=kolicina)
       {
           kolicina = kolicina - kolic;
           System.out.println("Napravena e naracka");
       }
       else{
          
           System.out.println("Nema dovolno lekovi");
       }
       
    
   
}
}
public class Lekovi {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {
        // TODO code application logic here
       
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
       
        String ime;
        int kolicina;
        int N = Integer.parseInt(br.readLine());
       
        CBHT<String, Lekche> tabela = new CBHT<String, Lekche>(N*2);
       
        for(int i=0;i<N;i++)
        {
           String []niza= br.readLine().split(" ");
           
           
           tabela.insert(niza[0], new Lekche(niza[0], Integer.parseInt(niza[1]), Integer.parseInt(niza[2]), Integer.parseInt(niza[3])));
           
        }
        System.out.println(tabela);
       
        while(true)
        {
           ime = br.readLine();
           if(ime.matches("KRAJ"))
           break;
           kolicina = Integer.parseInt(br.readLine());
           
           
          SLLNode<MapEntry<String, Lekche>> l =  tabela.search(ime);
         
          if(l==null)
          System.out.println("Ne postoi takov lek");
          else
          {
             
            Lekche lek = l.element.value; 
             
           lek.presmetaj(kolicina);
           
           System.out.println("od lekot: " + lek.ime + " ima preostanato uste " + lek.kolicina + " kolicina");
          }
         
         
          
        }
       
       
    }
   
}
 

Kajgana Shop

На врв Bottom