By GokiSoft.com| 17:21 23/03/2020|
Java Advanced

Share Code- Lession 2 - Generic + FileInputStream + FileOutputStream - T1907A

Phần 1 > Chữa bài tập HashMap


/*
 * 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 java2.lession2.student;

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**
 *
 * @author Diep.Tran
 */
public class Main {
    public static void main(String[] args) {
        Map<String, Student> studentHashMap = new HashMap<>();
        
        Scanner input = new Scanner(System.in);
        int choose;
        
        do {
            showMenu();
            choose = Integer.parseInt(input.nextLine());
            
            switch(choose) {
                case 1:
                    System.out.println("Nhap N: ");
                    int n = Integer.parseInt(input.nextLine());
                    for (int i = 0; i < n; i++) {
                        Student std = new Student();
                        std.input();
                        
                        studentHashMap.put(std.getRollNo(), std);
                    }
                    break;
                case 2:
                    System.out.println("Thong tin sinh vien");
                    for (Map.Entry<String, Student> entry : studentHashMap.entrySet()) {
                        Student value = entry.getValue();
                        value.display();
                    }
                    break;
                case 3:
                    System.out.println("Nhap MSV can tim kiem: ");
                    String rollNo = input.nextLine();
                    
                    Student stdFind = studentHashMap.get(rollNo);
                    if(stdFind != null) {
                        stdFind.display();
                    } else {
                        System.out.println("Ko tim thay sv voi MSV nhap vao");
                    }
                    break;
                case 4:
                    System.out.println("Exit!!!");
                    break;
            }
        } while(choose != 4);
    }
    
    static void showMenu() {
        System.out.println("1. Nhap N sinh vien");
        System.out.println("2. In thong tin sinh vien");
        System.out.println("3. Tim kiem sinh vien theo RollNo");
        System.out.println("4. Thoat");
        System.out.println("Chon: ");
    }
}



/*
 * 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 java2.lession2.student;

import java.util.Scanner;

/**
 *
 * @author Diep.Tran
 */
public class Student {
    String name, rollNo, sex, email, address;
    int age;

    public Student() {
    }

    public Student(String name, String rollNo, String sex, String email, String address, int age) {
        this.name = name;
        this.rollNo = rollNo;
        this.sex = sex;
        this.email = email;
        this.address = address;
        this.age = age;
    }
    
    public void input() {
        Scanner input = new Scanner(System.in);
        System.out.println("Nhap ten: ");
        name = input.nextLine();
        
        System.out.println("Nhap MSV: ");
        rollNo = input.nextLine();
        
        System.out.println("Nhap gioi tinh: ");
        sex = input.nextLine();
        
        System.out.println("Nhap Email: ");
        email = input.nextLine();
        
        System.out.println("Nhap dia chi: ");
        address = input.nextLine();
        
        System.out.println("Nhap tuoi: ");
        age = Integer.parseInt(input.nextLine());
    }

    @Override
    public String toString() {
        return "Student{" + "name=" + name + ", rollNo=" + rollNo + ", sex=" + sex + ", email=" + email + ", address=" + address + ", age=" + age + '}';
    }
    
    public void display() {
//        System.out.println(toString());
        System.out.println(this);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getRollNo() {
        return rollNo;
    }

    public void setRollNo(String rollNo) {
        this.rollNo = rollNo;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

Generic + File



/*
 * 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 java2.lession2;

import java.util.ArrayList;
import java.util.List;
import zoo.Animal;

/**
 *
 * @author Diep.Tran
 * @param <E>
 */
public class AnimalController<E extends Animal> {
    List<E> list;
    
    public AnimalController() {
        this.list = new ArrayList<>();
    }
    
    public void add(E e) {
        list.add(e);
    }
    
    public E get(int index) {
        return list.get(index);
    }
}



/*
 * 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 java2.lession2;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import zoo.Dog;

/**
 *
 * @author Diep.Tran
 */
public class Main {
    public static void main(String[] args) {
        //Tim hieu Generic
        //1. La cai j??? cach su dung ??? cach tao 1 generic rieng??
        List<Integer> list = new ArrayList<>();
        list.add(12);
        
        List<String> list2 = new ArrayList<>();
        list2.add("Abc");
        //List<Integer> && List<String> => no dc tao ra tu 1 class hay 2 class
        //Khang dinh >> List<Integer> && List<String> >> chinh la tu 1 class
        //van de dat ra
        //Tai sao list => quan ly so nguyen, list2 la String
        int t = list.get(0);//Dung
//        String str = list.get(0);//Sai
        
//        int t2 = list2.get(0);//sai
        String str2 = list2.get(0);//Dung
        //Cai nay nguoi ta goi no la Generic => ky thuat trong lap trinh (Java, C#, ...)
        
        Map<String, String> map = new HashMap<>();
        
        //cach tao 1 generic
        AnimalController<Dog> animalController = new AnimalController<>();
        animalController.add(new Dog());
        
//        AnimalController<Integer> list3 = new AnimalController<>();
//        list.add(123);
        //Lam the nao => AnimalController => Dong vat
    }
}



/*
 * 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 java2.lession2;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Diep.Tran
 */
public class Test {

    public static void main(String[] args) {
        //Tuong tac len du lieu ve FILE
        //Viet ra phan Window Explorer
//        File file = new File("build.xml");
//        if(file.exists()) {
//            System.out.println("Exist");
//            file.delete();
//        } else {
//            System.out.println("Not");
//            try {
//                file.createNewFile();
//            } catch (IOException ex) {
//                Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
//            }
//        }
        String filename = "vidu.txt";
//        FileOutputStream fos = null;
//        try {
//            //open connection (tao ket noi toi FILE)
//            fos = new FileOutputStream(filename);
//
//            //thuc tao tac doc/ghi du lieu
//            String str = "Hello World!!!";
//            byte[] data;
//            data = str.getBytes("utf8");
//            fos.write(data);
//        } catch (FileNotFoundException ex) {
//            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
//        } catch (UnsupportedEncodingException ex) {
//            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
//        } catch (IOException ex) {
//            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
//        } finally {
//            if (fos != null) {
//                try {
//                    //dong ket
//                    fos.close();
//                } catch (IOException ex) {
//                    Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
//                }
//            }
//        }
        FileInputStream fis = null;
         try {
             fis = new FileInputStream(filename);
             
             int code;
//             String str = "";
            StringBuilder builder = new StringBuilder();
             while((code = fis.read()) != -1) {
                 //convert code => ky tu tuong ung
                 char c = (char) code;
//                 str += String.valueOf(c);
                builder.append(c);
             }
             
//            System.out.println(str);
             System.out.println(builder.toString());
         } catch(Exception e) {
             e.printStackTrace();
         } finally {
             if(fis != null) {
                 try {
                     fis.close();
                 } catch (IOException ex) {
                     Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
                 }
             }
         }
    }
}

Xem Phần 2

Phản hồi từ học viên

5

(Dựa trên đánh giá ngày hôm nay)