By GokiSoft.com| 10:15 06/08/2021|
Java Advanced

[Share Code] Tìm hiểu về Exception + StringBuilder - StringBuffer + java.lang package trong Java - Lập trình Java nâng cao. BT2357



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

import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

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

    public static void main(String[] args) {
        int x, y;

        Scanner scan = new Scanner(System.in);

        System.out.println("Nhap x = ");
        x = scan.nextInt();

        System.out.println("Nhap y = ");
        y = scan.nextInt();

        //C1: Logic
        if (y == 0) {
            System.out.println("Ko dc phep chia cho 0");
        } else {
            int s = x / y;

            System.out.println("s = " + s);
        }
        
        //C2: Try .. Catch .. Finally
        try {
            int s = x / y;

            System.out.println("s = " + s);
        } catch(ArithmeticException e) {
            e.printStackTrace();
        } finally {
            System.out.println("Ket thuc ...");
        }
        
        StringBuilder builder = new StringBuilder();
        builder.append("1");
        builder.append("2");
        builder.append("3");
        builder.append("4");
        builder.append("5");
        builder.append("6");
        
        System.out.println(builder.toString());
        
        StringBuffer buffer = new StringBuffer();
        buffer.append("1");
        buffer.append("2");
        buffer.append("3");
        buffer.append("4");
        buffer.append("5");
        buffer.append("6");
        
        System.out.println(buffer.toString());
        
        scan.nextLine();
        //Test function trong String
        System.out.println("s1 = ");
        String s1 = scan.nextLine();
        
        System.out.println("s2 = ");
        String s2 = scan.nextLine();
        
        String[] list = s1.split(s2);
        
        for (String s : list) {
            System.out.println(s);
        }
        
        StringTokenizer tokenizer = new StringTokenizer(s1, s2);
        
        System.out.println("Token:");
        while(tokenizer.hasMoreTokens()) {
            System.out.println(tokenizer.nextToken());
        }
        
        //Kiem tra s1 co chua 1 chuoi nao do tuan thu theo quy tac sau khong
        //aba: a -> [a-z]{2,3}, b -> [0-9]{1,5}
        //[a-z]{2,3}[0-9]{1,5}[a-z]{2,3}
        Pattern pattern = Pattern.compile("[a-z]{2,3}[\\d]{1,5}[a-z]{2,3}");
        Matcher matcher = pattern.matcher(s1);
        
        while(matcher.find()) {
            System.out.println(matcher.group());
        }
    }
}




Tags:

Liên kết rút gọn:

https://gokisoft.com/2357

Bình luận