• Thế Giới Giải Mã

    Bí ẩn nhân loại Leonardo Da Vinci

  • Thế Giới Giải Mã

    Anh hùng thầm lặng Nikola Tesla

  • Thế Giới Giải Mã

    Thần đèn Thomas Edison

  • Thế Giới Giải Mã

    Người thôi miên Adolf Hitler

Showing posts with label Java Advanced. Show all posts
Showing posts with label Java Advanced. Show all posts

16 June 2017

Java OOP:Điều khiển click trên màn hình bằng Interface Java

Điều khiển click trên màn hình bằng Interface
Mobile.java
Java Core 2017
import java.util.ArrayList;
import java.util.List;

public class Mobile {
    public static void main(String[] args) {
        // Running application
        MainActivity main = new MainActivity(); // Tạo mới app và lấy data 1 lần duy nhất
        ContactAdapter adapter = main.runningApp(); // Tạo mới class adapter 1 lần duy nhất
        // Click icon tren danh sach man hinh (Bấm nhiều lần với 1 lần tạo mới class
        // Adapter)
        adapter.setOnClickListenerAdd(3); // Click vị trí số 3 trên màn hình
        adapter.setOnClickListenerEdit(2); // Click vị trí số 2 trên mà hình
    }
}

interface IOnChildItemClick {
    public void onItemChildClickEdit(int position);

    public void onItemChildClickAdd(int position);
}

class ContactAdapter {
    private IOnChildItemClick iOnChildItemClick;

    public void registerChildItemClick(IOnChildItemClick iOnChildItemClick) {
        this.iOnChildItemClick = iOnChildItemClick;
    }

    public void setOnClickListenerEdit(int position) {
        iOnChildItemClick.onItemChildClickAdd(position);
    }

    public void setOnClickListenerAdd(int position) {
        iOnChildItemClick.onItemChildClickEdit(position);
    }
}

class MainActivity implements IOnChildItemClick {
    static List<String> listAvatar;
    static List<Integer> listNumber;
    public ContactAdapter adapter;

    @Override
    public void onItemChildClickEdit(int position) {
        // TODO Auto-generated method stub
        if (position != 0) {
            System.out.println("Update Contact: " + listNumber.get(position) + " URL: " + listAvatar.get(position)
                    + " --> Position: " + position);
        }
    }

    @Override
    public void onItemChildClickAdd(int position) {
        // TODO Auto-generated method stub
        if (position != 0) {
            System.out.println("Add new Contact: " + listNumber.get(position) + " URL: " + listAvatar.get(position)
                    + "  --> Position: " + position);
        }
    }

    public ContactAdapter runningApp() {
        System.out.println("Start the program!");
        adapter = new ContactAdapter();
        adapter.registerChildItemClick(this);
        initData();
        return adapter;
    }

    public static void initData() {
        listAvatar = new ArrayList<String>();
        listAvatar.add("D:/xyz.jpg");
        listAvatar.add("D:/AyR.jpg");
        listAvatar.add("D:/CSKH.jpg");
        listAvatar.add("D:/IMUSIK.jpg");

        listNumber = new ArrayList<Integer>();
        listNumber.add(983919892);
        listNumber.add(1666161033);
        listNumber.add(19008198);
        listNumber.add(197);
    }
}
Hướng dẫn chạy online
Chạy chương trình online coppy source vào đây

05 May 2017

JUnit Test Basic vs Eclipse Java

Example 1
JUnit Test 2017
Bảng này chứ?package Test;

import org.junit.Test;
import static org.junit.Assert.assertTrue;

import model.Company;

public class demo {

 @Test
 public void testName(){
    Company c = new Company();
       c.setName("FPT");
       assertTrue(c.getName().equals("FPT"));
   }
 
 @Test
 public void testAddress(){
    Company c = new Company();
       c.setAddress("Hanoi");
       assertTrue(c.getAddress().equals("Hanoi"));
   }
}
Example 2
JUnit Test 2017

package Test;

import org.junit.Test;
import static org.junit.Assert.assertTrue;

import org.junit.BeforeClass;

import model.Company;

public class demo {

    public static Company c;

    //Khởi tạo cho tất cả
    @BeforeClass
    public static void prepareForAllTest() {
        c = new Company();
    }

    @Test
    public void testName() {
        c.setName("FPT");
        assertTrue(c.getName().equals("FPT"));
    }

    @Test
    public void testAddress() {
        c.setAddress("Hanoi");
        assertTrue(c.getAddress().equals("Hanoi"));
    }
}
Example 3
JUnit Test 2017
package Test;

import org.junit.Test;
import static org.junit.Assert.assertTrue;

import org.junit.Before;
import org.junit.BeforeClass;

import model.Company;

public class demo {

    public static Company c;

    @BeforeClass
    public static void prepareForAllTest() {
        c = new Company();
    }

    //Chuẩn bị cho testName
    @Before
    public void prepareTestName() {
        c.setName("FPT");
    }

    @Test
    public void testName() {
        assertTrue(c.getName().equals("FPT"));
    }

    @Test
    public void testAddress() {
        c.setAddress("Hanoi");
        assertTrue(c.getAddress().equals("Hanoi"));
    }
    @After
    public void closeTestName() {

    }

    @AfterClass
    public void closeForAllTest() {
        //Close database connect
    }
}


22 March 2017

SQL Server: Connect và Khắc phục lỗi Connection Database Sql Server vs JAVA JDBC

Bước 1: bạn cần download Driver JDBC dành cho SQL Server

Chọn file có đuôi exe
Giải nén thành công chúng ta sẽ sử dụng 1 trong 2 file này để sử dụng cho Connect Jre7 or Jre8
Bước 2: Cần thêm port 1433 cho TCP/IP của máy tính bạn

TCP/IP connection to the host Failed: Solution

The solution is to ensure that your SQL Server instance is listening on the port. Follow these steps to ensure that SQL SERVER 2014 is start listening on port 1433:
  1. Go to Start->All Programs-> Microsoft SQL Server 2012-> Configuration Tool
  2. Click SQL Server Configuration Manager
  3. Expand SQL Server Network Configuration-> Protocol
  4. Enable TCP/IP Right box
  5. Double Click on TCP/IP and go to IP Addresses Tap and Put port 1433 under TCP port.
Đây là lỗi khi chưa có port 1433
Java JDBC 2017
com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host 
localhost, port 1433 has failed. Error: "Connection refused: connect. 
Verify the connection properties. Make sure that an instance of SQL Server 
is running on the host and accepting TCP/IP connections at the port. 
Make sure that TCP connections to the port are not blocked by a firewall.
In Windows 8.1, you can also press Windows + c and click on Search icon to start searching for SQL Server Configuration Manager. Once found just click on it to open.

Anyway, once you got to the above screen just double click on highlighted TCP/IP link and this will open the following window, make sure you enter TCP Port as 1433. That's it.
That's all about how to fix The TCP/IP connection to the host localhost, port 1433 has failed error while connecting to SQL SERVER from Java using JDBC API. You also need to create user and logins in order to connect using JDBC and type 4 JDBC driver. I am going to post that information soon in next couple of articles.

Dưới đây là hai cách
Windows Store 2017
package com.fsoft.connect;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBConnection {

    private static Connection connection = null;

    public static Connection getConnection() {
        if (connection != null) {
            return connection;
        } else {
            try {
                Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
                connection = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databasename=MyDatabase", "sa", "12345678");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return connection;
        }
    }

    //Test connection database
    public static void main(String[] args) {
        System.out.println(getConnection());
    }
}
package com.demo.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectionFactory {

    //Cách này sử dụng tốt hơn
    private static ConnectionFactory instance = new ConnectionFactory();
    String url = "jdbc:sqlserver://localhost:1433;databaseName=MyDatabase";
    String user = "sa";
    String password = "12345678";
    String driverClass = "com.microsoft.sqlserver.jdbc.SQLServerDriver";

    //private constructor
    private ConnectionFactory() {
        try {
            Class.forName(driverClass);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static ConnectionFactory getInstance() {
        return instance;
    }

    public Connection getConnection() throws SQLException, ClassNotFoundException {
        Connection connection = DriverManager.getConnection(url, user, password);
        return connection;
    }
}
//--------------------------------------------------------------
//  Khi sử dụng - khuyên dùng cách 2 sẽ có điểm khác riêng biệt
//--------------------------------------------------------------
public class mockDAO {
    Connection connection;
    Statement stmt;
    PreparedStatement prestmt;
     
    private static Connection getConnection() throws SQLException, ClassNotFoundException {
        Connection con = ConnectionFactory.getInstance().getConnection();
        return con;
    }
    
    public List<Item> listItem(){
     String query = "SELECT * FROM Item";
     List<Item> list = new ArrayList<>();
     Item item = null;
     try{
      connection = getConnection();
      stmt = connection.createStatement();
      ResultSet rs = stmt.executeQuery(query);
      while(rs.next()){
       item = new Item(rs.getInt("ItemID"),rs.getString("ItemName"));
       list.add(item);
      }
     } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }finally
        {
            try {
                if(stmt != null)
                    stmt.close();
                if(connection != null)
                    connection.close();
                } catch (SQLException e) {
                e.printStackTrace();
            }
        }
     return list;
    }
}
Đây là thông báo Connect thành công của cách 1

20 March 2017

JDBC vs Connect SQL Server Insert Update Select Database JAVA

Write an application to allow the user to add or update his/her profile data to the trainees list of the application, details as described below:
-       On entering the application, the application show a menu as below:
1)    Add new account
2)    Update account
3)    Trainee list
-       If user choose add new account option, the user is asked to input account name, password, first-name, last-name, email. Those must not be empty.
-       When valid data are inputted, the user’s profile information would be added or updated into the database. The update occurs only in the case his/her account exists already.
-       When user choose trainee list option, the user would be redirected to the trainee list page which show all the accounts, each account is on a separated row.
-       Any input data validation or application exception must be handled. Warning and error messages must be shown to the user.

Other Requirements:
-       Use Microsoft SQL server as the database.
-       There is not any common defects in the applications
-       Use CheckStyle to specify & fix all the raised error messages


Estimated time: 180 mins
DButil.Java
Java Advanced 2017
package com.demo;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DButil {

    private static Connection connection = null;

    public static Connection getConnection() {
        if (connection != null) {
            return connection;
        } else {
            try {
                Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
                connection = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databasename=Employees", "sa", "12345678");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return connection;
        }
    }

    // Test connection database
    public static void main(String[] args) {
        System.out.println(getConnection());
    }

}
Account.Java
Java Advanced  2017
package com.demo;

public class Account {

    private String accName;
    private String password;
    private String firstName;
    private String lastName;
    private String email;

    public String getAccName() {
        return accName;
    }

    public String getPassword() {
        return password;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public String getEmail() {
        return email;
    }

    public Account(String accName, String password, String firstName,
            String lastName, String email) {
        super();
        this.accName = accName;
        this.password = password;
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
    }

    public Account() {
        super();
        // TODO Auto-generated constructor stub
    }

}
Menu.Java
Java Advanced 2017
package com.demo;

import java.util.Scanner;

public class Menu {

    Scanner s = new Scanner(System.in);

    // Khoi tao doi tuong logicOption va CheckNull
    LogicOption logicOption = new LogicOption();
    CheckNull checkNull = new CheckNull();

    public void start() {
        while (true) {

            int num = menu();
            switch (num) {
                case 1:
                    System.out.println("#Chose 1");
                    addAccount();
                    break;
                case 2:
                    System.out.println("#Chose 2");
                    updateAccount();
                    break;

                case 3:
                    System.out.println("#Chose 3");
                    displayAccount();
                    break;
                case 4:
                    System.out.println("#Chose 4");
                    System.out.println("Stop the program! Good bye!!");
                    logicOption.closeConnect(); //Dong ket noi
                    System.exit(0); // Thoat vong lap va ket thuc program
                    break;
                default:
                    break;

            }
        }
    }

    private void displayAccount() {
        logicOption.displayAcc(); // Hien thi all
    }

    private void updateAccount() {
        System.out.print("Check update AccName: ");
        String accName = s.nextLine();
        boolean b = logicOption.checkPrimaryKeys(accName); // Check accName
        if (b) {
            System.out.println("=========================================");
            System.out.println("|| Has found Please update this account||");
            System.out.println("=========================================");
            System.out.print("Enter your password: ");
            String password = s.nextLine();
            System.out.print("Enter your first name: ");
            String firstName = s.nextLine();
            System.out.print("Enter your last name: ");
            String lastName = s.nextLine();
            System.out.print("Enter your email: ");
            String email = s.nextLine();

            boolean b1 = checkNull.checkNull(accName, password, firstName, lastName, email);
            if (b1) {
                Account acc = new Account(accName, password, firstName, lastName, email);
                logicOption.updateAccount(acc);
            } else {
                checkNull.showErrorNull(accName, password, firstName, lastName, email, "update");
            }

        } else {
            System.out.println("|||||||||||||||||||||||||||||");
            System.out.println("|| AccName find not found! ||");
            System.out.println("/////////////////////////////");
        }

    }

    private void addAccount() {
        System.out.print("Enter your accName: ");
        String accName = s.nextLine();
        boolean b = logicOption.checkPrimaryKeys(accName); // Check accName
        if (!b) {
            System.out.print("Enter your password: ");
            String password = s.nextLine();
            System.out.print("Enter your first name: ");
            String firstName = s.nextLine();
            System.out.print("Enter your last name: ");
            String lastName = s.nextLine();
            System.out.print("Enter your email: ");
            String email = s.nextLine();

            boolean b1 = checkNull.checkNull(accName, password, firstName, lastName, email);
            if (b1) {
                //True Insert account
                Account acc = new Account(accName, password, firstName, lastName, email);
                logicOption.addAccount(acc); // Them moi account
            } else {
                //show message file null
                checkNull.showErrorNull(accName, password, firstName, lastName, email, "insert");
            }
        } else {
            System.out.println("||||||||||||||||||");
            System.out.println("|| Was existed! ||");
            System.out.println("//////////////////");
        }
    }

    public int menu() {
        System.out.println("1. Add new account");
        System.out.println("2. Update account");
        System.out.println("3. Display Contact");
        System.out.println("4. Exit");
        int num = 0;
        int check = Integer.parseInt(s.nextLine());
        if (check == 1 || check == 2 || check == 3 || check == 4) {
            num = check;
        } else {
            System.out.println("||||||||||||||||||||||");
            System.out.println("|| Xin moi chon lai ||");
            System.out.println("||||||||||||||||||||||");
        }
        return num; // Menu tra ve gia tri 1,2,3,4
    }
}
LogicOption.Java
Java Advanced 2017
package com.demo;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Formatter;
import java.util.Scanner;

public class LogicOption {

    private Connection conn = null;
    private PreparedStatement pstmt = null;
    private ResultSet rs;

    Scanner s = new Scanner(System.in);

    public LogicOption() {
        conn = DButil.getConnection();
    }

    public void addAccount(Account account) {

        String insertQuery = "INSERT INTO dbo.account (accName ,password ,firstName,lastName, email) VALUES (?,?,?,?,?)";
        try {
            pstmt = conn.prepareStatement(insertQuery);
            pstmt.setString(1, account.getAccName());
            pstmt.setString(2, account.getPassword());
            pstmt.setString(3, account.getFirstName());
            pstmt.setString(4, account.getLastName());
            pstmt.setString(5, account.getEmail());

            pstmt.executeUpdate();
            System.out.println("Add account success!\n");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void updateAccount(Account account) {

        String sql = "UPDATE dbo.account SET password = ?, firstName = ?,lastName = ?, email = ?  WHERE accName=?";
        try {
            pstmt = conn.prepareStatement(sql);

            pstmt.setString(1, account.getPassword());
            pstmt.setString(2, account.getFirstName());
            pstmt.setString(3, account.getLastName());
            pstmt.setString(4, account.getEmail());
            pstmt.setString(5, account.getAccName());
            pstmt.executeUpdate();
            System.out.println("Update account success!\n");
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    public boolean checkPrimaryKeys(String accName) {
        String sql = "SELECT * FROM dbo.Account Where accName =?";
        try {
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, accName);

            rs = pstmt.executeQuery();
            while (rs.next()) {
                String accName1 = rs.getString("accName");
                if (accName1.equalsIgnoreCase(accName)) {
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public void displayAcc() {
        String sql = "SELECT * FROM dbo.Account";
        Formatter formatter = new Formatter();
        try {
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            System.out.println("-----------------------------------------------------------------");
            System.out.println("AccName || Password || FistName || LastName || Email");
            while (rs.next()) {
                String accName = rs.getString("accName");
                String password = rs.getString("password");
                String firstName = rs.getString("firstName");
                String lastName = rs.getString("lastName");
                String email = rs.getString("email");
                System.out.println(accName + "   " + password + "   " + firstName + "   " + lastName + "    " + email);

            }
            System.out.println("------------------------------------------------------------------");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void closeConnect() {
        try {
            pstmt.close();
            rs.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
CheckNull.Java
Java Advanced 2017
package com.demo;

public class CheckNull {

    public boolean checkNull(String accName, String password, String firstName,
            String lastName, String email) {
        if (accName.length() == 0) {
            return false;
        } else if (accName.length() == 0) {
            return false;
        } else if (password.length() == 0) {
            return false;
        } else if (firstName.length() == 0) {
            return false;
        } else if (lastName.length() == 0) {
            return false;
        } else if (email.length() == 0) {
            return false;
        } else {
            return true;
        }

    }

    public void showErrorNull(String accName, String password,
            String firstName, String lastName, String email, String type) {
        if (accName.length() == 0) {
            System.out.println("===================NULL=====================");
            System.out.println("|| Account Name NULL! Please " + type + " again ||");
            System.out.println("============================================");
        } else if (password.length() == 0) {
            System.out.println("================NULL===================");
            System.out.println("|| Password NULL! Please " + type + " again ||");
            System.out.println("========================================");
        } else if (firstName.length() == 0) {
            System.out.println("==================NULL===================");
            System.out.println("|| First Name NULL! Please " + type + " again ||");
            System.out.println("=========================================");
        } else if (lastName.length() == 0) {
            System.out.println("==================NULL===================");
            System.out.println("|| Last Name NULL! Please " + type + " again ||");
            System.out.println("=========================================");
        } else if (email.length() == 0) {
            System.out.println("=========================================");
            System.out.println("|| Email Name NULL! Please " + type + " again ||");
            System.out.println("==========================================");
        } else {
            System.out.println();
        }

    }
}
Computer.Java
Java Advanced 2017
package com.demo;

public class Computer {

    public static void main(String[] args) {
        Menu menu = new Menu();
        menu.start();
    }
}

19 March 2017

Ví dụ về tính đa hình Interface Abstract Class trong JAVA hiển thị Console

Interface > Abstract > Class Extends và Override method tư interface
Shape.Java
Java 2017
package Java2;

public interface Shape {

    void getArea();
    void getVolume();
}
TwoDimensionalShape.Java

Java Advanced 2017
package Java2;

public abstract class TwoDimensionalShape implements Shape {

    @Override
    public void getArea() {
        // TODO Auto-generated method stub
    }

    @Override
    public void getVolume() {
        // TODO Auto-generated method stub
    }

}
ThreeDimensionalShape.Java
Java Advanced 2017
package Java2;

public abstract class ThreeDimensionalShape implements Shape {

    @Override
    public void getArea() {
        // TODO Auto-generated method stub
    }

    @Override
    public void getVolume() {
        // TODO Auto-generated method stub
    }

}
Circle.Java
Java Advanced 2017
package Java2;

public class Circle extends TwoDimensionalShape {

    private final double PI = 3.14f;
    private double r, S;

    public Circle(double r) {
        super();
        this.r = r;
        Calculature();
    }

    public double getPI() {
        return PI;
    }

    public double getR() {
        return r;
    }

    public void Calculature() {
        S = Math.round(PI * getR() * PI);
    }

    @Override
    public void getArea() {
        // TODO Auto-generated method stub
        // S = PI*R*2
        System.out.println("Dien tich hinh tron: " + S);
    }

}
Square.Java
Java Advanced 2017
package Java2;

public class Square extends TwoDimensionalShape {

    private int a;

    public int getA() {
        return a;
    }

    public Square(int a) {
        super();
        this.a = a;
    }

    @Override
    public void getArea() {
        // TODO Auto-generated method stub
        //S = a²
        System.out.println("Dien tich hinh vuong: " + Math.round(getA() * getA()));
    }

}
Triangle.Java
Java Advanced 2017
package Java2;

public class Triangle extends TwoDimensionalShape {

    private int b; //b chieu dai canh day
    private int h; //h: chieu cao

    public int getB() {
        return b;
    }

    public int getH() {
        return h;
    }

    public Triangle(int b, int h) {
        super();
        this.b = b;
        this.h = h;
    }

    @Override
    public void getArea() {
        // TODO Auto-generated method stub
        //S = (b*h)/2  
        int a = getB() * getH();
        System.out.println("Dien tich hinh tam giac: " + a / 2);
    }
}
Sphere.Java
Java Advanced 2017
package Java2;

public class Sphere extends ThreeDimensionalShape {

    private double r; //Ban kinh
    private final double PI = 3.14d;
    private double S, V;

    public Sphere(double r) {
        super();
        this.r = r;
        Calculature();
    }

    public double getR() {
        return r;
    }

    public void Calculature() {
        //S=4*PI*R^2
        double R2PI = PI * getR() * getR();
        S = 4 * R2PI;
        //v = 3/4 *PI * R^3
        V = (3 * R2PI * getR()) / 4;
    }

    @Override
    public void getArea() {
        // TODO Auto-generated method stub
        System.out.println("Dien tich cua hinh cau: " + Math.round(S));
    }

    @Override
    public void getVolume() {
        // TODO Auto-generated method stub
        System.out.println("The tich hinh cau: " + Math.round(V));
    }

}
Cube.Java
Java Advanced 2017
package Java2;

public class Cube extends ThreeDimensionalShape {

    private int a;

    public int getA() {
        return a;
    }

    public Cube(int a) {
        super();
        this.a = a;
    }

    @Override
    public void getArea() {
        // TODO Auto-generated method stub
        // S = 6a²
        System.out.println("Dien tich hinh lap phuong: " + 6 * (getA() * getA()));

    }

    @Override
    public void getVolume() {
        // TODO Auto-generated method stub
        // V = a x a x a
        System.out.println("The tich hinh lap phuong: " + getA() * getA() * getA());

    }

}
Tetrahedron.Java
Java Advanced 2017
package Java2;

public class Tetrahedron extends ThreeDimensionalShape {

    private int a, b, c, h; // abc canh tam giac, h la chieu cao
    private int P, result, S;
    private boolean check = false;

    public int getA() {
        return a;
    }

    public int getB() {
        return b;
    }

    public int getC() {
        return c;
    }

    public int getH() {
        return h;
    }

    public int getP() {
        return P;
    }

    public int getResult() {
        return result;
    }

    public Tetrahedron(int a, int b, int c, int h) {
        super();
        this.a = a;
        this.b = b;
        this.c = c;
        this.h = h;
        calculature();

    }

    public int getS() {
        return S;
    }

    public boolean check() {
        if (getA() + getB() > getC()) {
            if (getA() + getC() > getB()) {
                if (getC() + getB() > getA()) {
                    check = true;
                } else {
                    System.out.println("Nhap sai gia tri B or C");
                }
            } else {
                System.out.println("Nhap sai gia tri A or C");
            }
        } else {
            System.out.println("Nhap sai gia tri A or B");
        }

        return check;
    }

    public void calculature() {
        P = (getA() + getB() + getC()) / 2;
        result = P * (P - getA()) * (P - getB()) * (P - getC());
        S = (int) Math.sqrt(result);
    }

    @Override
    public void getArea() {
        // TODO Auto-generated method stub
        // p = (a + b + c) /2
        // S =(SQRT) p[p-a][p-b][p-c]
        System.out.println("Dien tich hinh tu dien : " + S);
    }

    @Override
    public void getVolume() {
        // TODO Auto-generated method stub
        // V = 1/3 * S*h
        System.out.println("The tich hinh tu dien: " + (S * h) / 3);
        check();

    }

}
Main.Java
Java Advanced 2017
package Java2;

import java.util.ArrayList;
import java.util.List;

public class Main {

    public static void main(String[] args) {

        List<Shape> list = new ArrayList<Shape>();

        Shape c = new Circle(5);// r2
        Shape s = new Square(5);// a
        Shape t = new Triangle(4, 6);// a canh, h chieu cao

        Sphere s1 = new Sphere(6); // r
        Cube c1 = new Cube(9);// a
        Tetrahedron t1 = new Tetrahedron(9, 8, 12, 2); // a,b,c,h

        list.add((Shape) c);
        list.add((Shape) s);
        list.add((Shape) t);
        list.add((Shape) s1);
        list.add((Shape) c1);
        list.add((Shape) t1);

        // Output 1
        System.out.println("\nDIEN TICH CUA CAC HINH\n");
        for (Shape item : list) {
            item.getArea();
        }
        System.out.println("\nTHE TICH CUA CAC HINH\n");
        for (Shape item : list) {
            item.getVolume();
        }

    }

}

 

BACK TO TOP

Xuống cuối trang