Tuesday, May 28, 2013

Batch 102A - A guide to advance Java

Hi All,
     Minh gui cac ban ma nguon thuc hanh. Moi nguoi co gang download ve, go lai cac dong code va chay chuong trinh. Neu ai chua hieu thi lien he de hoi minh nhe.

    [27-05-2013] Introduction to Thread
    [29-05-2013] More on Thread (download ve, giai nen, tim den bai searchPrimesThread)

    [6-5-2013 ] ArrayListdDemo

    [14-06-2013] Copy File


Good luck!

16 comments:

  1. class employee1 {
    public String name;
    public String Phone;
    public int age;
    public double salary;
    public employee1(String name, String Phone, int age, double salary){
    this.name = name;
    this.Phone = Phone;
    this.age = age;
    this.salary = salary;
    }
    public void display(){
    System.out.println("Name: "+this.name +
    " - Phone: "+this.Phone+
    " - age: "+this.age +
    " - salary: "+this.salary);
    }
    }
    public class ArrayListDemo {
    public static void main(String[] args){
    employee1 emp1 = new employee1("Alice","0905432123",24,6000000);
    emp1.display();
    }
    }

    ReplyDelete
  2. package advancejava;

    import java.util.ArrayList;

    /**
    *
    * @author quangdong
    */
    class employee1 {
    public String name;
    public String Phone;
    public int age;
    public double salary;
    public employee1(String name, String Phone, int age, double salary){
    this.name = name;
    this.Phone = Phone;
    this.age = age;
    this.salary = salary;
    }
    public void display(){
    System.out.println("Name: "+this.name +
    " - Phone: "+this.Phone+
    " - age: "+this.age +
    " - salary: "+this.salary);
    }
    }
    public class ArrayListDemo {
    public static void main(String[] args){
    //employee1 emp1 = new employee1("Alice","0905432123",24,6000000);
    //emp1.display();

    employee1[] emp = new employee1[10];
    for (int i=0; i<10;i++){
    emp[i]= new employee1("Alice "+i, "090512312"+i,
    (int)(100*Math.random()),
    Math.round(10000000* Math.random()));
    }
    System.out.println("Array size: "+ emp.length);
    // emp[5].display();
    // emp[6].display();

    ArrayList empList = new ArrayList();
    employee1 tmp;
    for (int i=0; i<20;i++){
    tmp = new employee1("Alice "+i, "090512312"+i,
    (int)(100*Math.random()),
    Math.round(10000000* Math.random()));
    empList.add(tmp);
    }

    employee1 mytmp = (employee1)empList.get(5);
    mytmp.display();
    System.out.println("Arraylist size: "+ empList.size());
    }
    }

    ReplyDelete
  3. import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.Vector;

    /**
    *
    * @author quangdong
    */
    class employee1 {
    public String name;
    public String Phone;
    public int age;
    public double salary;
    public employee1(String name, String Phone, int age, double salary){
    this.name = name;
    this.Phone = Phone;
    this.age = age;
    this.salary = salary;
    }
    public void display(){
    System.out.println("Name: "+this.name +
    " - Phone: "+this.Phone+
    " - age: "+this.age +
    " - salary: "+this.salary);
    }
    }
    public class ArrayListDemo {
    public static void main(String[] args){
    //su dung vector
    Vector v = new Vector();
    employee1 tmp;
    tmp = new employee1("Alice1", "0905123121",
    (int)(100*Math.random()),
    Math.round(10000000* Math.random()));
    v.addElement(tmp);
    tmp = new employee1("Alice2", "0905123122",
    (int)(100*Math.random()),
    Math.round(10000000* Math.random()));
    v.addElement(tmp);
    v.addElement(tmp);
    System.out.println("Vector size: "+ v.size());
    System.out.println("Vector capacity: "+ v.capacity());

    int size = v.size();
    for(int i=0;i<size;i++){
    tmp = (employee1)v.get(i);
    tmp.display();
    }

    Iterator iter = v.iterator();
    while (iter.hasNext()){
    tmp = (employee1)iter.next();
    tmp.display();
    }
    }
    }

    ReplyDelete
  4. Thầy ơi cho e hỏi : Khi e viết chương trình với Thread hay bị lỗi thứ tự thực thi của các Thread (e có tham khảo phương thức isAlive() với join() trong ví dụ của Thầy nhưng vẫn chạy không đúng .. )
    code :
    package Learn_Java;
    import java.util.Scanner;

    public class Modulo_1{
    public Modulo_1() {
    }
    public static void main(String[] args) {
    Scanner Input = new Scanner(System.in);
    MyThread MT = new MyThread();
    int NumberOfThread ;
    System.out.println("Program Find primes in the interval [1,1000] using threads");
    do{
    System.out.print("You want to execute the program with how many thread (Enter : 1, 2, 4 or 5) : ");
    NumberOfThread = Input.nextInt();
    }while(NumberOfThread<1 || NumberOfThread>5 || NumberOfThread==3);
    MT.ExecutedWithThread(NumberOfThread);
    }
    }
    class MyThread extends Thread{
    public MyThread() {
    }
    public MyThread(int Min , int Max){
    this.Min = Min ;
    this.Max = Max ;
    }
    int Term , Count=0 , Min , Max ;
    boolean Check = true ;
    private static final int Start = 1000 ;
    @Override
    public void run(){
    System.out.println("Primes from : " + Min + " to " + Max + " : ");
    for(Term=Min+1 ; Term<Max ; Term++){
    for(int j=2 ; j<=Math.sqrt(Term) ; j++){
    if(Term%j==0){
    Check = false ; break ;
    }
    }
    if(Check){
    Count++ ;
    System.out.print(Term + "\t");
    if(Count==10){
    Count = 0 ;
    System.out.println();
    }
    }else{
    Check = true ;
    }
    }
    System.out.println("\n");
    }
    public void ExecutedWithThread(int NumberOfThread){
    int Increase = Start/NumberOfThread ;
    System.out.println("\nFind primes in the interval [" + Start/1000 + "," + Start + "] using "
    + NumberOfThread + " Threads. Is executed ...\n");
    MyThread[] Executed = new MyThread[NumberOfThread];
    for(int i=0 ; i<NumberOfThread ; i++){
    Executed[i] = new MyThread(1+i*Increase , (1+i)*Increase);
    Executed[i].start();
    }
    for(int i=0 ; i<NumberOfThread ; i++) {
    while(Executed[i].isAlive()) {
    try {
    Executed[i].join();
    } catch (InterruptedException e) {
    }
    }
    }
    }
    }
    result :
    Program Find primes in the interval [1,1000] using threads
    You want to execute the program with how many thread (Enter : 1, 2, 4 or 5) : 5

    Find primes in the interval [1,1000] using 5 Threads.

    Primes from : 1 to 200 :
    2 3 5 7 11 13 17 19 23 29
    31 37 41 43 47 53 59 61 67 71
    73 79 83 89 97 101 103 107 109 113
    127 131 137 139 149 151 157 163 167 173
    179 181 191 193 197 199

    Primes from : 201 to 400 :
    211 223 227 229 233 239 241 251 257 263
    269 271 277 281 283 293 307 311 313 317
    331 337 347 349 353 359 367 373 379 383
    389 397

    Primes from : 801 to 1000 :
    809 811 821 823 827 829 839 853 857 859
    863 877 881 883 887 907 911 919 929 937
    941 947 953 967 971 977 983 991 997

    Primes from : 401 to 600 :
    409 419 421 431 433 439 443 449 457 461
    463 467 479 487 491 499 503 509 521 523
    541 547 557 563 569 571 577 587 593 599


    Primes from : 601 to 800 :
    607 613 617 619 631 641 643 647 653 659
    661 673 677 683 691 701 709 719 727 733
    739 743 751 757 761 769 773 787 797

    (e phải chạy 5 hay 6 lần thì chương trình mới chia ra được 5 Thread riêng như vậy .. nhưng thứ tự vẫn không đúng .. có cách sửa không Thầy .. Hướng dẫn e với)

    ReplyDelete
  5. /*
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    */
    package javaapplication1;

    import java.util.Scanner;

    /**
    *
    * @author Fresher180
    */
    public class JavaApplication1 extends Thread{

    public int start;
    public int end;
    public int numberthread;
    public JavaApplication1(){

    }
    public JavaApplication1(int start,int end){
    this.start=start;
    this.end=end;
    //.numberthread=numberthread;

    }
    public void Input(){
    Scanner sc = new Scanner(System.in);
    System.out.println("Input the start number: ");
    start=sc.nextInt();
    System.out.println("Input the end number: ");
    end=sc.nextInt();
    }
    public void InputThread(){
    Scanner sc = new Scanner(System.in);
    System.out.println("Input number Thread: ");
    numberthread = sc.nextInt();
    }
    public boolean Check(int end){

    //int a = (int)Math.sqrt(end);

    int count=0;

    for(int i=1;i<=end;i++){
    if(end%i==0){
    count++;
    }
    }if(count==2){
    return true;
    }else return false;
    }
    public void CreatThread(){
    //System.out.println(numberthread);
    int z=end-start;
    int x=(int)(z/numberthread);
    JavaApplication1 j[] = new JavaApplication1[numberthread];
    for(int i=0;i<=numberthread-1;i++){
    j[i] = new JavaApplication1(start,end=start+x);
    start=start+x;
    }
    for(int i=0;i<=numberthread-1;i++){
    j[i].start();
    }
    }
    public void run(){

    for(int i=start;i<=end;i++){
    if(Check(i)==true){
    System.out.println(" "+i);
    }
    }
    }
    /**
    * @param args the command line arguments
    */
    public static void main(String[] args) {
    JavaApplication1 j1 = new JavaApplication1(10,100);
    j1.Input();
    j1.InputThread();
    j1.CreatThread();
    //j1.start();
    }
    }

    ReplyDelete
  6. @Nam Nguyễn: Chao Nam, khi em chay Thread, cac Thread duoc thuc thi doc lap nhau nen viec xuat ra cac ket qua khong lien tuc la chuyen binh thuong. Neu em muon dieu khien de no xuat ra lien tuc thi chang khac nao em chi su dung 1 thread de tim so nguyen to.
    + Phuong thuc isAlive() la de kiem tra xem 1 thread co con ton tai hay da ket thuc.
    + Phuong thuc join() dung khi 1 thread muon cho doi 1 thread khac ket thuc truoc khi no ket thuc.

    ReplyDelete
  7. import java.io.FileInputStream;

    /**
    *
    * @author quangdong
    */
    public class ReadFile {

    public static void main(String[] args) {
    FileInputStream testFile = null;
    StringBuffer buff = new StringBuffer();

    try {

    testFile = new FileInputStream("D:\\test.txt");
    boolean Eof = false;
    //trong luc chua den cuoi file thi doc du lieu
    while (!Eof){

    int byteVal = testFile.read();//doc 1 byte ky tu
    buff.append((char)byteVal);

    System.out.println("So bytes da doc duoc: "+byteVal);

    if (byteVal== -1 ) Eof = true;
    }

    System.out.println("Noi dung: " + buff.toString());
    } catch (Exception ex) {
    ex.printStackTrace();
    }finally{
    try{
    testFile.close();
    }catch(Exception ex1){ex1.printStackTrace();}
    }

    }
    }

    ReplyDelete

  8. import java.io.FileOutputStream;
    /**
    *
    * @author quangdong
    */
    public class ReadFile {
    public static void main(String[] args) {
    FileOutputStream testWrite = null;
    try {

    testWrite = new FileOutputStream("D:\\test1.txt");

    String str = "write to a file abcd";

    byte [] b = str.getBytes();
    testWrite.write(b);


    } catch (Exception ex) {
    ex.printStackTrace();
    }finally{
    try{
    testWrite.close();
    }catch(Exception ex1){ex1.printStackTrace();}
    }

    }
    }

    ReplyDelete
  9. package advancejava;

    import java.lang.reflect.Field;

    /**
    *
    * @author quangdong
    */

    class employee {
    public String name;
    public int age;
    public String Phone;
    }
    public class Reflection_Demo {
    public static void printObject(Object obj){
    Class objClass = obj.getClass();
    Field [] allField = objClass.getFields();
    int size = allField.length;
    String FieldName ;
    Class typeClass ;
    String FileType ;
    System.out.println("Object has some Following Attributes");
    for (int i=0; i<size;i++){
    FieldName = allField[i].getName();
    typeClass = allField[i].getType();
    FileType = typeClass.getName();
    System.out.println("Name: '"+ FieldName +"' type: '"+FileType+"'");
    }
    }
    public static void main(String [] args){
    employee em = new employee();
    printObject(em);

    }
    }

    ReplyDelete
  10. import java.lang.reflect.Constructor;
    import java.lang.reflect.Field;

    /**
    *
    * @author quangdong
    */

    class employee {
    public String name;
    public int age;
    public String Phone;
    public employee(String name){

    }
    public employee(String name, int age){

    }
    public employee(String name, int age, String phone){

    }
    }
    public class Reflection_Demo {
    public static void printObject(Object obj){
    Class objClass = obj.getClass();
    Field [] allField = objClass.getFields();
    int size = allField.length;
    String FieldName ;
    Class typeClass ;
    String FileType ;
    System.out.println("Object has some Following Attributes");
    for (int i=0; i<size;i++){
    FieldName = allField[i].getName();
    // typeClass = allField[i].getType();
    FileType = allField[i].getType().getName();
    System.out.println("Name: '"+ FieldName +"' type: '"+FileType+"'");
    }
    }
    public static void printConstructor(Object obj){
    Class objclass = obj.getClass();
    Constructor[] allConstructor = objclass.getConstructors();
    int size = allConstructor.length;
    for (int j=0;j<size;j++){
    System.out.println("(");
    Class[] parameterType = allConstructor[j].getParameterTypes();
    for (int k=0;k<parameterType.length;k++){
    String paramString = parameterType[k].getName();
    System.out.println(paramString+ " ");

    }
    System.out.println(")");

    }


    }
    public static void main(String [] args){
    employee em = new employee("alice");
    printObject(em);
    System.out.println(" ------------------");
    printConstructor(em);
    }
    }

    ReplyDelete
  11. //in ra tat ca cac phuong thuc cua mot doi tuong
    public static void printAllMethod(Object obj){
    Class objClass = obj.getClass();
    Method [] allMethod = objClass.getMethods();
    for (int i=0;i<allMethod.length;i++){
    //lay ve ten phuong thuc
    String methodString = allMethod[i].getName();
    System.out.println("Ten phuong thuc: "+methodString);
    //lay kieu du lieu tra ve cua phuong thuc
    String returnType = allMethod[i].getReturnType().getName();
    //lay tham so truyen vao cho phuog thuc
    Class [] parameterType = allMethod[i].getParameterTypes();
    System.out.print("Cac Tham so can truyen: ");
    for (int k=0;k<parameterType.length;k++){
    String ParameterString = parameterType[k].getName();
    System.out.print(" "+ ParameterString);
    }
    System.out.println("");

    }

    }

    ReplyDelete
  12. import java.util.regex.*;
    /**
    *
    * @author quangdong
    */
    public class RegularExpression1 {
    public static void main(String [] args){
    String Str1;
    Str1 = "xin";
    String Str2 = "xin chao bạn";
    System.out.println("Chuoi ban dau: "+ Str1);

    System.out.println("Chuoi can tim la: " + Str2);

    Pattern ptnSearch = Pattern.compile(Str1,Pattern.CASE_INSENSITIVE);

    Matcher mtrtext = ptnSearch.matcher(Str2);

    // if(mtrtext.matches()){
    // System.out.println("Tim duoc chuoi: "+Str2);
    //
    // }else{
    // System.out.println("Khong tim duoc choi tuong ung");
    // }

    boolean find = false;
    while (mtrtext.find()){
    System.out.println("Tim duoc chuoi tuong thich: "+Str2);
    System.out.println("Start: "+ mtrtext.start() + " end at: "+mtrtext.end());
    find= true;
    }

    if (!find) System.out.println("Khong tim duoc chuoi tuong thich");


    }

    }

    ReplyDelete
  13. This comment has been removed by the author.

    ReplyDelete
  14. import java.awt.FlowLayout;
    import javax.swing.JButton;
    import javax.swing.JCheckBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JTextField;

    /**
    *
    * @author quangdong
    */
    public class JFrameDemo extends JFrame {
    public JTextField txtname;
    public JLabel lblname;
    public JButton btnexit;
    public JCheckBox chkdem;
    public JFrameDemo(String tittle){
    super(tittle);
    this.setSize(400, 400);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setLayout(new FlowLayout());
    initComponent();
    this.setVisible(true);
    }
    private void initComponent(){
    lblname =new JLabel("Demo: ");
    txtname = new JTextField("This is a demo text");
    btnexit = new JButton("Exit");
    this.add(lblname);
    this.add(txtname);
    this.add(btnexit);




    }
    }

    ReplyDelete
  15. tao. form thu' 2 , co' 1 nut button BACK , lam sao no' quay lai form kia thay`, que^n cach' lam`

    ReplyDelete
  16. http://www.mediafire.com/?wp55k0imuayg9jg

    ReplyDelete