17:29
0
Java (đọc như "Gia-va") là một ngôn ngữ lập trình dạng lập trình hướng đối tượng (OOP). Khác với phần lớn ngôn ngữ lập trình thông thường, thay vì biên dịch mã nguồn thành mã máy hoặc thông dịch mã nguồn khi chạy, Java được thiết kế để biên dịch mã nguồn thành bytecode, bytecode sau đó sẽ được môi trường thực thi (runtime environment) chạy. Bằng cách này, Java thường chạy chậm hơn những ngôn ngữ lập trình thông dịch khác như C++, Python, Perl, PHP, C#...

Chú ý: những bài (*) là những bài khó nha các bạn.

Bài 3.2: Design and implement an application that reads an integer value rep-resenting a year from the user. The purpose of the program is todetermine if the year is a leap year (and therefore has 29 days in February) in the Gregorian calendar. A year is a leap year if it is divisible by 4, unless it is also divisible by 100 but not 400. For example, the year 2003 is not a leap year, but 2004 is. The year 1900 is not a leap year because it is divisible by 100, but the year 2000 is a leap year because even though it is divisible by 100, it is also divisible by 400. Produce an error message for any input value less than 1582 (the year the Gregorian calendar was adopted). (Kiểm tra năm nhuần tạo số ngẫu nhiên)
Code
import java.util.Random;
import java.util.Scanner;

public class bai2 {

	static int nhap(String thongbao)
	{
		int x;
		System.out.println(thongbao);
		Scanner scan = new Scanner(System.in);
		x = scan.nextInt();
		return x;
	}
	
	
	static void xuat(int n)
	{
		for (int i = 0; i < n; i++) {
			int year;
			Random rad = new Random();
			year = rad.nextInt(3000);
			
			do {
				year = rad.nextInt(3000);
			} while (year < 1528 || year > 2020);
			
			
			if (kiemtranamnhuan(year)) {
				System.out.println("Năm " + year +  " là năm nhuần.");
			}
			else {
				System.out.println("Năm " + year + " không phải là năm nhuần.");
			}
			
		}		
	}
	
	static boolean kiemtranamnhuan(int year)
	{		
		if (year%4 == 0 && !(year % 100 == 0 && year % 400 != 0)) {
			return true;
		}
		else {
			return false;
		}		
	}
	
	public static void main(String[] args) {
		System.out.println("Chương trình kiểm tra năm nhuần tạo năm bằng Random.");
		int n;
		n = nhap("Bạn hãy nhập số lương năm cần kiểm tra.");
		xuat(n);
	}

}
Bài 3.3:  Modify the solution to the previous project so that the user can eval-uate multiple years. Allow the user to terminate the program using an appropriate sentinel value. Validate each input value to ensure it is greater than or equal to 1582.(Kiểm tra năm nhuần nhập vào)
Code
import java.util.Scanner;

public class bai2 {

	static int nhap(String thongbao)
	{
		int x;
		System.out.println(thongbao);
		Scanner scan = new Scanner(System.in);
		x = scan.nextInt();
		return x;
	}
	
	
	static void xuat(int year)
	{
			if (year <= 1582) {
				System.err.println("Năm bạn nhập phải lớn hơn 1582");
			}
			else
			{
				if (kiemtranamnhuan(year)) {
					System.out.println("Năm bạn vừa nhâp là năm nhuần.");
				}
				else {
					System.out.println("Năm bạn vừa nhâp không phải là năm nhuần.");
				}
			}
	}
	
	static boolean kiemtranamnhuan(int year)
	{		
		if (year%4 == 0 && !(year % 100 == 0 && year % 400 != 0)) {
			return true;
		}
		else {
			return false;
		}		
	}
	
	public static void main(String[] args) {
		System.out.println("Chương trình kiểm tra năm nhuần khi người dùng nhập vào.");
		int n = nhap("Bạn hãy nhập số năm cần kiểm tra:");
		xuat(n);
	}

}
Bài 3.4: Design and implement an application that reads an integer value and prints the sum of all even integers between 2 and the input value, inclusive. Print an error message if the input value is less than 2. Prompt accordingly.
Code:
/*----------------- BAI 3.4 ---------------*/
import java.util.Scanner;
public class bai3_4 {

	static int nhap(String thongbao)
	{
		int x;
		System.out.print(thongbao);
		Scanner scan = new Scanner(System.in);
		x = scan.nextInt();
		return x;
	}
	
	public static void main (String[] args)
	{
		System.out.println("Chương trình xuất ra tổng từ 2 đến giá trị nhập vào");  
		int n, sum; 		
		n =nhap("Bạn hãy nhập số muốn tính tổng bắt đầu là 2: ");
		sum = Tongdayso(n);
		System.out.println("Tổng giữa 2 đến " + n + " là : " + sum);     
	}
	
	/*Ham tinh tong giua 2 toi gia tri nhap vao*/
	static int Tongdayso(int n)
	{
		int sum = 0;
		if (n < 2){ 
		       System.out.println("Số bạn nhập vào phải lớn hơn 2.");
		}
		else 
		{
			for (int i=2; i<=n; i+=2){
				sum += i;				
			}
		}
		return sum;
	}
}
Bài 3.5: Design and implement an application that reads a string from theuser and prints it one character per line.
Code:
/*----------------- BAI 3.5 ---------------*/
import java.util.Scanner;
public class bai3_5 {

	static String nhap(String thongbao)
	{
		String x;
		System.out.println(thongbao);
		Scanner scan = new Scanner(System.in);
		x = scan.next();
		return x;
	}
	
	public static void main (String[] args)
	{
		System.out.println("Chương trình xuất ra 1 ký tự trên 1 dòng");  
		String chuoi="";
		chuoi = nhap("Bạn hãy nhập vào một chuỗi cần muốn xuất: ");
		XuatChuoi(chuoi);
		XuatChuoi02(chuoi);
	}
	
	/*Hàm xuất từng ký tự trên 1 chuỗi*/
	static void XuatChuoi(String s)
	{
		char curent;
		int count = 0 ;
		int chieudai = s.length();
		for (int i = 0; i < chieudai; i++) {
			curent = s.charAt(i);
			count++;
			System.out.println(curent);
		}
		System.out.println("Chuỗi bạn nhập vào là \"" + s + "\" có " + count + " ký tự. hehe...");
	}
	
	/*Hàm xuất từng ký tự trên 1 chuỗi*/
	/*Hàm nâng cao chạy trong ForEach*/
	static void XuatChuoi02(String s)
	{
		char curent;
		int count = 0 ;
		for (char c : s.toCharArray()) {
			curent = c;
			count++;
			System.out.println(curent);
		}
		System.out.println("Chuỗi bạn nhập vào là \"" + s + "\" có " + count + " ký tự. huhu...");
	}
	
}
Bài 3.6: Design and implement an application that determines and prints the number of odd, even, and zero digits in an integer value read from the keyboard.
Code:
/*----------------- BAI 3.6 ---------------*/
import java.util.Scanner;
public class bai3_6 {

	static String nhap(String thongbao)
	{
		String x;
		System.out.print(thongbao);
		Scanner scan = new Scanner(System.in);
		x = scan.next();
		return x;
	}
	
	public static void main (String[] args)
	{
		System.out.println("Chương trình xuất ra bao nhiêu số lẻ, số chẵn và số 0");  
		String chuoi="";
		chuoi = nhap("Bạn hãy nhập giá trị vào: ");
		XuatSo(chuoi);
		
	}
	
	/*Hàm xuất từng ký tự trên 1 chuỗi*/
	static void XuatSo(String s)
	{
		char curent;
		int CountOld = 0, CountEven = 0, CountZero = 0 ;
		int chieudai = s.length();
		
		for (int i = 0; i < chieudai; i++) {
			curent = s.charAt(i);		
			// Lấy giá trị của chuỗi
			//Ép kiểu dữ liệu
			int number = Integer.parseInt(Character.toString(curent));
			if (number == 0) {
				CountZero++;
			}
			else if (number %2==0 ) {
				CountEven++;
			}else {
				CountOld++;
			}			
		}	
		
		System.out.println("Số bạn nhập vào là \"" + s + "\"");			
		System.out.println("có \"" + CountZero + "\" số Zero(0)");
		System.out.println("có \"" + CountEven + "\" số Chẵn(Even)");
		System.out.println("có \"" + CountOld + "\" số lẻ(Old)");
	}	
}
Code C2:
package ngoctrongweek2;

import java.util.Scanner;
public class Bai3_6 {
	
	// Ham nhap so
	static long nhap(String thongbao)
	{
		long x;
		System.out.print(thongbao);
		Scanner keyboard = new Scanner(System.in);
		x = keyboard.nextLong();
		return x;
	}
	
	//Ham main
	public static void main(String[] args) {
		System.out.println("Chương trình đếm số Chẵn, số Lẻ và Số Zero");		
		char Q;
		do {
			long n = nhap("Bạn hãy nhập dãy số cần đếm: ");			
			System.out.println();
			//khong su dung de quy
			XuatDem(n);
			//su dung de quy
			System.out.println();
			System.out.println("Bạn hãy nhập dãy số cần đếm: " + n);
			System.out.println("---------------- SỬ DỤNG ĐỆ QUY ----------------");
			XuatDemDeQuy(n);
			System.out.println("Bạn có muốn tiếp tục không?(y/n)");
			Q = new Scanner(System.in).nextLine().charAt(0);			
		} while (Q == 'y' || Q == 'Y');		
	}
	
	//Ham Xuat ra so chan, le va so 0 | Khong dung de quy
	static void XuatDem(long n)
	{
		System.out.println("------------ KHÔNG SỬ DỤNG ĐỆ QUY ---------");
		// khởi tạo 3 biến đếm
		int demchan=0;
		int demle=0;
		int demzero=0;
		//Khởi tạo 3 mảng để sắp xếp phần tử
		long[] intArrayChan = new long[100];
		long[] intArrayLe = new long[100];
		long[] intArrayZero = new long[100];
		
		long x = 0;		
		do {
			x = n % 10;			
			if (x % 2 == 0) {				
				if (x != 0) {
					intArrayChan[demchan] = x;
					demchan++;				
				}
				else {
					intArrayZero[demzero] = x;
					demzero++;					
				}							
			}
			else {
				intArrayLe[demle] = x;
				demle++;				
			}
			
			n = n / 10;			
			
			if (n == 0) {
				demzero ++;
			}
			
		} while (n > 0);		
		
		//****************************************************
		//****************************************************
		// Selection Sort (Sắp xếp chọn lựa) dành cho SỐ CHẴN
		//****************************************************
		//****************************************************
		System.out.print("Dãy số chẵn là: ");		
		for (int i = 0; i < demchan; i++)
        {
			// Lưu phần tử lớn nhất
			int max = (int) intArrayChan[i]; 
			// lưu vị trí chứa phần tử lớn nhất
            int index = i; 
            // vị trí phần tử lớn nhất +1
            for (int j = i + 1; j < demchan; j++)
            {
            	//nếu lớn hơn thì thay max bằng số vị trí array[j]
            	if (max < intArrayChan[j])
                {
                    max = (int) intArrayChan[j];
                    index = j;
                }
            }
            
            // Nếu chỉ số đã thay đổi, ta sẽ hoán vị
            if (index != i)
            {
                int temp = (int) intArrayChan[i];	
                intArrayChan[i] = intArrayChan[index];
                intArrayChan[index] = temp;
            }
        }

		for (int i = 0; i < demchan; i++) {
			System.out.print(intArrayChan[i] + " ");
		}
		System.out.print("\nSố Chẵn trong dãy số có \"" + demchan + "\" số.");
		System.out.print("\n---|-------------------------");	
		
		
		//****************************************************
		//****************************************************
		//Bubble Sort (Sắp xếp nổi bọt) dành cho SỐ LẺ
		//****************************************************
		//****************************************************
		for (int i = 0; i < demle; i++)
		{
			for (int j = intArrayLe.length - 1; j > 0; j--)
			{
				//nếu  phần tử bên  phải ( array[j] ) mà lớn hơn pt 
				//bên trái  array[j - 1]  thì 2 pt sẽ hoán đổi vị trí cho nhau
				if (intArrayLe[j] > intArrayLe[j - 1])
				{
					// lưu phần tử  array[j]  vào  biến  temp
					int temp = (int) intArrayLe[j];
					intArrayLe[j] = intArrayLe[j - 1];
					intArrayLe[j - 1] = temp;
				}
			}
		}
				
		System.out.print("\nDãy số chẵn lẻ: ");
		for (int i = 0; i < demle; i++) {
			System.out.print(intArrayLe[i] + " ");
		}
		System.out.print("\nSố Lẻ trong dãy số có \"" + demle + "\" số.");
		System.out.print("\n---|-------------------------");
		
		//****************************************************
		//****************************************************
		//Không sắp xếp dành cho SỐ ZERO(0)
		//****************************************************
		//****************************************************
		System.out.print("\nDãy số Zero là: ");
		for (int i = 0; i < demzero; i++) {
			System.out.print(intArrayZero[i] + " ");
		}
		System.out.print("\nSố Zero trong dãy số có \"" + demzero + "\" số.");
		System.out.println("\n---|-------------------------");
	}
	
	

	// khởi tạo 3 biến đếm
	static int demchan=0;
	static int demle=0;
	static int demzero=0;
	//Khởi tạo 3 mảng để sắp xếp phần tử
	static long[] intArrayChan = new long[100];
	static long[] intArrayLe = new long[100];
	static long[] intArrayZero = new long[100];	
	
	//Ham Xuat ra so chan, le va so 0 | Dung de quy	
	static void XuatDemDeQuy(long n)
	{			
		long x = 0;		
		x = n % 10;			
		if (x % 2 == 0) {				
			if (x != 0) {
				intArrayChan[demchan] = x;
				demchan++;				
			}
			else {
				intArrayZero[demzero] = x;
				demzero++;					
			}							
		}
		else {
			intArrayLe[demle] = x;
			demle++;				
		}

		n = n / 10;			
		if (n == 0) {
			demzero ++;
		}
		//************************************
		
		if (n > 0) {
			XuatDemDeQuy(n);
		}
		// hết thì cho xuất...
		else {
			
			//****************************************************
			//****************************************************
			// Selection Sort (Sắp xếp chọn lựa) dành cho SỐ CHẴN
			//****************************************************
			//****************************************************
			System.out.print("Dãy số chẵn là: ");		
			for (int i = 0; i < demchan; i++)
	        {
				// Lưu phần tử lớn nhất
				int max = (int) intArrayChan[i]; 
				// lưu vị trí chứa phần tử lớn nhất
	            int index = i; 
	            // vị trí phần tử lớn nhất +1
	            for (int j = i + 1; j < demchan; j++)
	            {
	            	//nếu lớn hơn thì thay max bằng số vị trí array[j]
	            	if (max < intArrayChan[j])
	                {
	                    max = (int) intArrayChan[j];
	                    index = j;
	                }
	            }
	            
	            // Nếu chỉ số đã thay đổi, ta sẽ hoán vị
	            if (index != i)
	            {
	                int temp = (int) intArrayChan[i];	
	                intArrayChan[i] = intArrayChan[index];
	                intArrayChan[index] = temp;
	            }
	        }

			for (int i = 0; i < demchan; i++) {
				System.out.print(intArrayChan[i] + " ");
			}
			System.out.print("\nSố Chẵn trong dãy số có \"" + demchan + "\" số.");
			System.out.print("\n---|-------------------------");	
			
			
			//****************************************************
			//****************************************************
			//Bubble Sort (Sắp xếp nổi bọt) dành cho SỐ LẺ
			//****************************************************
			//****************************************************
			for (int i = 0; i < demle; i++)
			{
				for (int j = intArrayLe.length - 1; j > 0; j--)
				{
					//nếu  phần tử bên  phải ( array[j] ) mà lớn hơn pt 
					//bên trái  array[j - 1]  thì 2 pt sẽ hoán đổi vị trí cho nhau
					if (intArrayLe[j] > intArrayLe[j - 1])
					{
						// lưu phần tử  array[j]  vào  biến  temp
						int temp = (int) intArrayLe[j];
						intArrayLe[j] = intArrayLe[j - 1];
						intArrayLe[j - 1] = temp;
					}
				}
			}
					
			System.out.print("\nDãy số chẵn lẻ: ");
			for (int i = 0; i < demle; i++) {
				System.out.print(intArrayLe[i] + " ");
			}
			System.out.print("\nSố Lẻ trong dãy số có \"" + demle + "\" số.");
			System.out.print("\n---|-------------------------");
			
			//****************************************************
			//****************************************************
			//Không sắp xếp dành cho SỐ ZERO(0)
			//****************************************************
			//****************************************************
			System.out.print("\nDãy số Zero là: ");
			for (int i = 0; i < demzero; i++) {
				System.out.print(intArrayZero[i] + " ");
			}
			System.out.print("\nSố Zero trong dãy số có \"" + demzero + "\" số.");
			System.out.println("\n---|-------------------------");
		}					
	}
	
}

Bài 3.7: Design and implement an application that produces a multiplication table, showing the results of multiplying the integers 1 through 12 by themselves.
Code:
/*----------------- BAI 3.7 ---------------*/
import java.util.Scanner;
public class bai2 {

	static int nhap(String thongbao)
	{
		int x;
		System.out.print(thongbao);
		Scanner scan = new Scanner(System.in);
		x = scan.nextInt();
		return x;
	}
	
	public static void main (String[] args)
	{
		System.out.println("Chương trình xuất ra bảng cửu chương từ 1 đến giá trị nhập vào");  
		int n;
		n = nhap("Bạn hãy nhập giá trị vào: ");
		XuatBangCuuChuong(n);		
	}
	
	/*Hàm xuất bảng cửu chương*/
	static void XuatBangCuuChuong(int n)
	{
		System.out.print("N");
		for (int m = 1; m <= n; m++) {
			System.out.print("\t" + m);
		}
		System.out.println("");
		System.out.println("-----------------------------------------");
		for (int i = 1; i <= n; i++) {
			System.out.print(i + " | \t");
			for (int j = 1; j <= n; j++) {
				System.out.print(j*i + "\t");
			}
			System.out.println("");
		}		
	}	
}
Bài 3.8: Modify the  CountWordsprogram so that it does not include punctu-ation characters in its character count.  Hint : This requires changing the set of delimiters used by the StringTokenizerclass.
Code
//---------- Bai 3.8
import java.util.StringTokenizer;
import java.util.Scanner;

public class bai3_8 {

	static String nhap(String thongbao)
	{
		String x;
		System.out.println(thongbao);
		Scanner keyboard = new Scanner(System.in);
		x = keyboard.nextLine();
		return x;		
	}
	
	public static void main(String[] args) {
		System.out.println("Chuong trinh xuat chuoi bang ky tu phan cach nhap vao");
		String s = nhap("Ban hay nhap chuoi muon tach");
		TachChuoi(s);
	}
	
	//Ham tach chuoi theo StringTokenizer
	static void TachChuoi(String s)
	{
		// hien thi chuoi moi tach
		String hienthi = "";
		// nhap vao dieu kien de tach chuoi
		String dktach = nhap("Ban hay nhap dieu kien de tach: ");
		
		StringTokenizer token = new StringTokenizer(s, dktach);
		while (token.hasMoreTokens()) {
			hienthi = token.nextToken();
			System.out.println(hienthi);
		}
	}
}
Bài 3.9: Create a revised version of the  Counter2 program such that the printlnstatement comes before the counter increment in the body of the loop. Make sure the program still produces the same output.
Code
//---------- Bai 3.9

import java.util.Scanner;
public class Bai3_9 {

	static int nhap(String thongbao)
	{
		int x;
		System.out.println(thongbao);
		Scanner keyboard = new Scanner(System.in);
		x = keyboard.nextInt();
		return x;		
	}
	
	
	public static void main (String[] args)
	{
		int n;
		n = nhap("Ban hay nhap so n can hien thi.");
		Counter2Modefy(n);
	}
	
	static void Counter2Modefy(int n)
	{
		final int LIMIT = n;
		System.out.println ("Done - OK");
		int count = 0;
		do
		{
			count += 1;
			System.out.println (count);
		}
		while (count < LIMIT);
	}
}

Bài 3.10:Design and implement an application that prints the first few verses of the traveling song “One Hundred Bottles of Beer” Use a loop such that each iteration prints one verse. Read the number of verses to print from the user. Validate the input. The following are the first two verses of the song:
(Bài hát 100 chai bia)
100 bottles of beer on the wall
100 bottles of beer
If one of those bottles should happen to fall
99 bottles of beer on the wall
99 bottles of beer on the wall
99 bottles of beer
If one of those bottles should happen to fall
98 bottles of beer on the wall
...................................
..................................
...................................
Code
//---------- Bai 3.10
import java.util.Scanner;
public class Bai3_10{
	
	static int nhap(String thongbao)
	{
		int x;
		System.out.println(thongbao);
		Scanner keyboard = new Scanner(System.in);
		x = keyboard.nextInt();
		return x;		
	}
	
	
	public static void main(String[] args)
    {
		int SoDong;
		char Q ;

		do {
			SoDong = nhap("Ban hay nhap so luong bia can hien thi");

			
			while(SoDong < 0 || SoDong > 100)
			{
				System.err.println("So dong tho ban nhap phai lon hon 0 va nho hon 100");
				SoDong = nhap("Ban hay nhap so luong bia can hien thi");
			}

			for(int i = 100; i > 100 - SoDong; i--)
			{
				System.out.println("\n" + i + " bottles of beer on the wall");
				System.out.println("\n" + i + " bottles of beer");
				System.out.println("\nIf one of those bottles should happen to fall");
				System.out.println("\n" + (i - 1) + " bottles of beer on the wall");
			}
			
			System.out.print("Ban co muon tiep tuc khong?(y/n)");
			Q = new Scanner(System.in).nextLine().charAt(0);
			
		} while (Q == 'y');
    }
}
Bài 3.11 (*): Design and implement an application that plays the Hi-Lo guessing game with numbers. The program should pick a random number between 1 and 100 (inclusive), then repeatedly prompt the user to guess the number. On each guess, report to the user that he or she is correct or that the guess is high or low. Continue accepting guesses until the user guesses correctly or chooses to quit. Use a sentinel value to determine whether the user wants to quit. Count the num-ber of guesses and report that value when the user guesses correctly. At the end of each game (by quitting or a correct guess), prompt to determine whether the user wants to play again. Continue playing games until the user chooses to stop. (Game Đoán Số)
Code:
//--------- BÀI 3.11 -----
import java.util.Random;
import java.util.Scanner;

public class Bai3_11
{
	static int nhap(String thongbao)
	{
		int x;
		System.out.println(thongbao);
		Scanner keyboard = new Scanner(System.in);
		x = keyboard.nextInt();
		return x;		
	}
	
	static void XuatGameHILO()
	{
		char Q;
		int solanchoi=0;
		final int MAX = 100;
		int answer, guess;
		Random generator = new Random(); 				
		do {							
			System.out.print("Số bạn đoán là: ");
			guess = nhap("");		
			answer = generator.nextInt(MAX) +1;
			System.out.println("--|--------------------------------------");
			System.out.println("Số bạn đoán là: " + guess + " | Số hệ thống là: " + answer);
			System.out.println("--|--------------------------------------");
			if (guess == answer){
				System.out.println ("Chúc mừng bạn đã đoán chúng!");
			}		
			else if (guess == 0){
				System.out.println ("Bạn đã kết thúc game HI-LO!");
			}			
			else if(guess != answer && guess != 0){
				if (guess > answer){ 
					System.out.println ("Số bạn đoán lớn hơn số hệ thống");					
				}
				else{
					System.out.println ("Số bạn đoán nhỏ hơn số hệ thống");						
				}
			}
			
			System.out.println("--|--------------------------------------");
			System.out.println("Bạn có muốn tiếp tục chơi nữa không?(y/n)");
			Q = new Scanner(System.in).nextLine().charAt(0);
			solanchoi++;
		} while (Q == 'Y' || Q== 'y');	
		
		System.out.println("Số lần bạn chơi game HI-LO là: " + solanchoi);
	}
	
	public static void main (String[] args)
	{
		System.out.println("Chào mừng bạn đến với Game HI-LO.(Đoán số)");
		System.out.println("Bạn hãy đón số trong khoản từ 1 đến 100");
		System.out.print("Số bạn đoán là(hoăc 0 đế thoát): ");
		XuatGameHILO();
	}
}
Bài 3.12(*): Create a modified version of the  PalindromeTester program so that the spaces, punctuation, and changes in uppercase and lower-case are not considered when determining whether a string is a palindrome. Hint : These issues can be handled in several ways. Think carefully about your design.
Code
/---------- Bai 3.12
import java.util.Scanner;
public class Bai3_12 {
	
	static String NhapChuoi(String thongbao)
	{
		String s;
		System.out.println(thongbao);
		Scanner keyboard = new Scanner(System.in);
		s = keyboard.nextLine();
		return s;		
	}
	
	public static void main(String[] args)
	{		
		System.out.println("Chuong trinh kiem tra chuoi nhap vao la Palindrome");		
		String s = NhapChuoi("Ban hay nhap chuoi can kiem tra:");
		//Chu thuong
		palindrome(s.toLowerCase());
		//Chu hoa
		//palindrome(s.toUpperCase());	
	}
		
	//------------- KIEM TRA CHUOI CO PHAI LA PALIDROME -------------
	static void palindrome(String s)
	{		
		int n=s.length();
		String str = "";
		for(int i=n-1; i>=0 ; i--)
			str += s.charAt(i);
			if(str.equals(s))
				System.out.println(s + " is palindrome");
			else
				System.out.println(s + " is not a palindrome");
	}		
}
Bài 3.13d(*): Create modified versions of the Starsprogram to print the follow-ing patterns. Create a separate program to produce each pattern. Hint:Parts b, c, and d require several loops, some of which print a specific number of spaces.
Code
//---------- Bai 3.13d
import java.util.Scanner;
public class Bai3_13d {

	static int Nhap(String thongbao)
	{
		int x;
		System.out.println(thongbao);
		Scanner keyboard = new Scanner(System.in);
		x = keyboard.nextInt();
		return x;
	}

	public static void main(String[] args) {
		//n la so dong hien thi
		int n = Nhap("Ban hay nhap so dong de hien thi ky tu *");
		XuatKimCuong(n);		    
	}
	
	static void XuatKimCuong(int n)
	{
		//k dung de in ra khoang trang

		int  i , j , k;       
		k = (n%2==0) ? n-1: n;                       

		//Vong lap thu nhat cho nua vien kiem cuong dau
		for(  i = 0  ;  i < n/2  ;  i++ )         
		{
			for( j = 0 ; j < k / 2 - i ; j++ )   //vong lap in khoang trang
				System.out.print(" ");
			for ( j = 0 ; j < i * 2 + 1 ; j++ )  //Vong lap in ra sao
				System.out.print("*");
			System.out.println();                //Xuong dong
		}

		//Vong lap cho dong sao le.
		if( n % 2 != 0)                           
		{
			for( i = 0 ; i < n ; i++ )             
				System.out.print("*");
			System.out.println();                  
		}

		//Vong lap thu ba cho nua vien kiem cuong cuoi
		for( i = n/2-1  ;  i >= 0  ;  i-- )       
		{
			for( j = 0 ; j < k/2 - i ; j++ )     //vong lap in khoang trang
				System.out.print(" ");
			for( j = 0 ; j < i*2+1 ; j++ )       //Vong lap in ra sao
				System.out.print("*");	             
			System.out.println();                //Xuong dong
		} 
		
	}
}
Bài 3.14:Design and implement an application that prints a table showing a subset of the Unicode characters and their numeric values. Print five number/character pairs per line, separated by tab characters. Print the table for numeric values from 32 (the space character) to 126 (the  ~  character), which corresponds to the printable ASCII subset of the Unicode character set. Compare your output to the table in Appendix C. Unlike the table in Appendix C, the values in your table can increase as they go across a row.
Code
//---------- Bai 3.14
public class Bai3_14 {

	public static void main(String[] args) {
		System.out.println("Chuong trinh xuat ra gia tri nguyen tuong ung voi 1 ma ASCII.");
		final int PER_COLUMN = 5;
		int count = 0;
		for (int x = 32; x <= 126; x++) 
		{
			char c = (char)x;
			System.out.print (x + " - " + c  + "\t    ");
			
			count++;

			if (count % PER_COLUMN == 0) {
				System.out.println();
			}
		}
	}
}
Bài 3.15:Design and implement an application that reads a string from the user, then determines and prints how many of each lowercase vowel (a, e, i, o, and u) appear in the entire string. Have a separate counter for each vowel. Also count and print the number of nonvowel char-acters.
Code
//---------- Bai 3.15
import java.util.Scanner;
public class Bai3_15 {
	
	static String NhapChuoi(String thongbao)
	{
		String s;
		System.out.println(thongbao);
		Scanner keyboard = new Scanner(System.in);
		s = keyboard.nextLine();
		return s;		
	}
	
	public static void main(String[] args)
	{		
		System.out.println("/**Chuong trinh xuat ky tu nguyen am(a, e, i, o, u)");
		System.out.println("/**Chuoi bat dau la vi tri 0.");		
		String s = NhapChuoi("Ban hay nhap chuoi can dem chu nguyen am");
		XuatChuoi(s.toLowerCase());
	}

	//------------- XUAT DEM CHUOI NGUYEN AM -------------
	static void XuatChuoi(String s)
	{	
		int dema = 0, deme = 0, demi = 0, demo = 0, demu = 0 ;
		System.out.println("Chuoi ban nhap vao la: " + s);
		for(int i=0; i < s.length(); i++)
		{
			if(s.charAt(i) == 'a')
			{
				System.out.println("Vi tri cua \"a\" la: " + i);
				dema++;
			}
			else if(s.charAt(i) == 'e')
			{
				System.out.println("Vi tri cua \"e\" la: " + i);
				deme++;
			}
			else if(s.charAt(i) == 'i')
			{
				System.out.println("Vi tri cua \"i\" la: " + i);
				demi++;
			}
			else if(s.charAt(i) == 'o')
			{
				System.out.println("Vi tri cua \"o\" la: " + i);
				demo++;
			}
			else if(s.charAt(i) == 'u')
			{
				System.out.println("Vi tri cua \"u\" la: " + i);
				demu++;
			}
		}
		System.out.println("\"a\" co: " + dema);
		System.out.println("\"e\" co: " + deme);
		System.out.println("\"i\" co: " + demi);
		System.out.println("\"o\" co: " + demo);
		System.out.println("\"u\" co: " + demu);
	}
}
Bài 3.16 (*): Design and implement an application that plays the Rock-Paper-Scissors game against the computer. When played between two peo-ple, each person picks one of three options (usually shown by a hand gesture) at the same time, and a winner is determined. In the game, Rock beats Scissors, Scissors beats Paper, and Paper beats Rock. The program should randomly choose one of the three options (without revealing it), then prompt for the user’s selection. At that point, the program reveals both choices and prints a statement indicating if the user won, the computer won, or if it was a tie. Continue playing until the user chooses to stop, then print the number of user wins, losses, and ties.(Game BÚA - KÉO - BAO)
Code
//---------- BÀI 3.16
import java.util.Random;
import java.util.Scanner;

public class Bai3_16 {
        
    // Hàm nhập vật dụng.
	static String nhap(String thongbao)
	{
		String s;
		System.out.println(thongbao);
		Scanner keyboard = new Scanner (System.in);
		s = keyboard.nextLine();
		return s;
	}
	
	// Hàm Main 
    public static void main(String[] args) 
    {
      System.out.println("Chào mừng bạn đến với trò chơi Rock(búa), Scissor(kéo), Paper(bao)?");
      XuatGameBKB();            
    }
    
    // Hàm xử lý game BÚA - KÉO - BAO
    static void XuatGameBKB()
    {
    	Random generator = new Random();
        int win = 0, tie = 0, lose = 0, solanchoi=0;
        char Q;
        do {    	      	  
        	String choice = nhap("Bạn hãy nhập vào tên vật dụng không dấu?");
        	// Chọn BÚA
        	if (choice.equalsIgnoreCase("bua")) {
        		int comp = generator.nextInt(3);
        		if (comp == 1)
        		{
        			System.out.println("Bạn đã \"Thắng\".");
        			win++;
        		}
        		else if (comp == 2)
        		{
        			System.out.println("Bạn đã \"Thua\".");
        			lose++;
        		}
        		else
        		{
        			System.out.println("Bạn đã \"Hòa\".");
        			tie++;
        		}            
        		SelectComputer(comp);
        	}
        	// Chọn BAO
        	else if (choice.equalsIgnoreCase("bao")) {
        		int comp = generator.nextInt(3);
        		if (comp == 1)
        		{        		
        			System.out.println("Bạn đã \"Thua\".");
        			lose++;
        		}
        		else if (comp == 0)
        		{
        			System.out.println("Bạn đã \"Thắng\".");	
        			win++;
        		}
        		else
        		{
        			System.out.println("Bạn đã \"Hòa\".");
        			tie++;
        		}

        		SelectComputer(comp);
        	}
        	// Chọn KÉO
        	else if (choice.equalsIgnoreCase("keo")) {
        		int comp = generator.nextInt(3);
        		if (comp == 2)
        		{        		
        			System.out.println("Bạn đã \"Thắng\".");
        			win++;
        		}
        		else if (comp == 0)
        		{        		
        			System.out.println("Bạn đã \"Thua\".");
        			lose++;
        		}
        		else
        		{
        			System.out.println("Bạn đã \"Hòa\".");
        			tie++;
        		}    
        		SelectComputer(comp);
        	}
        	System.out.println("--||---------------------------");
        	System.out.println("Bạn có muốn chơi lại không? (y/n)");    	  
        	Q = new Scanner(System.in).nextLine().charAt(0);    	
        	solanchoi++;
        } while (Q == 'y' || Q == 'Y');
        
        // Tổng kết số lần Thắng, Thua, Hòa và đếm số lần chơi game
        System.out.println("------------------ | | --------------------");
        System.out.println("Tổng kết số lần Thắng, Thua và Hòa");
        System.out.println("Số lần bạn chơi game này là: " + solanchoi);
        System.out.println("Số lần THẮNG: " + win);
        System.out.println("Số lần THUA: " + lose);
        System.out.println("Số lần HÒA: " + tie);    
    }
    
    //Hàm gọi máy tính của bạn chọn 3 trong 1 dụng cụ đó.
    static void SelectComputer(int comp){
    	if (comp == 0)
    	{
    		System.out.println("Máy tính của bạn đã chọn BÚA");
    	}
    	else if (comp == 1)
    	{
    		System.out.println("Máy tính của bạn đã chọn KÉO");
    	}
    	else if (comp == 2)
    	{
    		System.out.println("Máy tính của bạn đã chọn BAO");
    	}    	    	
    }
}
Bài 3.17(*): Design and implement an application that prints the verses of the song “The Twelve Days of Christmas” in which each verse adds one line. The first two verses of the song are:
(Bài thơ 12 ngày giáng sinh)
On the 1st day of Christmas my true love gave to me
A partridge in a pear tree.
On the 2nd day of Christmas my true love gave to me
Two turtle doves, and
A partridge in a pear tree.
..................................
...................................
....................................
Code
//---------- Bai 3.17
public class Bai3_17 {

	static void XuatTho()
	{
        //Tạo 1 mảng để chứa 12 câu thơ trong bài
		//Ký tự % ở câu 1 là vị trí thứ 1 mình sẽ dùng nó để Replace 
		//để lấy ra số thứ tự ngày.
        String[] arrLyrics;
            arrLyrics = new String[13];
            arrLyrics[0] = "On the % day of Christmas, my true love gave to me";
            arrLyrics[1] = "A partridge in a pear tree.";
            arrLyrics[2] = "Two turtle doves, and";
            arrLyrics[3] = "Three French hens,";
            arrLyrics[4] = "Four calling birds,";
            arrLyrics[5] = "Five golden rings,";
            arrLyrics[6] = "Six geese a laying,";
            arrLyrics[7] = "Seven swans a swimming,";
            arrLyrics[8] = "Eight maids a milking,";
            arrLyrics[9] = "Nine ladies dancing,";
            arrLyrics[10] = "Ten lords a leaping,";
            arrLyrics[11] = "Eleven pipers piping,";
            arrLyrics[12] = "Twelve drummers drumming,";        

            // Dòng for cho chạy từ 1 đến nhỏ hớn 13
            // Dùng Switch  - Case để lấy số câu thơ
        for (int i = 1; i < 13; i++){
        	// Biến day là chỉ số thứ tự ngày
            String day;
            String dailyLyric;
            switch(i){
                    case 1:
                        day = "st";
                        dailyLyric = arrLyrics[0].replace("%", i + day);
                        System.out.println(dailyLyric);
                        System.out.println("- " + arrLyrics[i]);
                        break;
                   case 2:
                        day = "nd";
                        dailyLyric = arrLyrics[0].replace("%", i + day);
                        System.out.println("\n" + dailyLyric);
                        //Vòng lặp để lấy ra số câu thơ tương ứng.
                        for (int j = 1; j <= i; j++) {                        	
                        	System.out.println("- " + arrLyrics[j]);
						}                        
                        break;
                   case 3:
                        day = "rd";
                        dailyLyric = arrLyrics[0].replace("%", i + day);
                        System.out.println("\n" + dailyLyric);
                        for (int j = 1; j <= i; j++) {                        	
                        	System.out.println("- " + arrLyrics[j]);
						}    
                        break;
                   case 4:
                        day = "th";
                        dailyLyric = arrLyrics[0].replace("%", i + day);
                        System.out.println("\n" + dailyLyric);
                        for (int j = 1; j <= i; j++) {                        	
                        	System.out.println("- " + arrLyrics[j]);
						}    
                        break;
                   case 5:
                        day = "th";
                        dailyLyric = arrLyrics[0].replace("%", i + day);
                        System.out.println("\n" + dailyLyric);
                        for (int j = 1; j <= i; j++) {                        	
                        	System.out.println("- " + arrLyrics[j]);
						}    
                        break;
                   case 6:
                        day = "th";
                        dailyLyric = arrLyrics[0].replace("%", i + day);
                        System.out.println("\n" + dailyLyric);
                        for (int j = 1; j <= i; j++) {                        	
                        	System.out.println("- " + arrLyrics[j]);
						}    
                        break;
                   case 7:
                        day = "th";
                        dailyLyric = arrLyrics[0].replace("%", i + day);
                        System.out.println("\n" + dailyLyric);
                        for (int j = 1; j <= i; j++) {                        	
                        	System.out.println("- " + arrLyrics[j]);
						}    
                        break;
                   case 8:
                        day = "th";
                        dailyLyric = arrLyrics[0].replace("%", i + day);
                        System.out.println("\n" + dailyLyric);
                        for (int j = 1; j <= i; j++) {                        	
                        	System.out.println("- " + arrLyrics[j]);
						}    
                        break;
                   case 9:
                        day = "th";
                        dailyLyric = arrLyrics[0].replace("%", i + day);
                        System.out.println("\n" + dailyLyric);
                        for (int j = 1; j <= i; j++) {                        	
                        	System.out.println("- " + arrLyrics[j]);
						}    
                        break;
                   case 10:
                        day = "th";
                        dailyLyric = arrLyrics[0].replace("%", i + day);
                        System.out.println("\n" + dailyLyric);
                        for (int j = 1; j <= i; j++) {                        	
                        	System.out.println("- " + arrLyrics[j]);
						}    
                        break;
                   case 11:
                        day = "th";
                        dailyLyric = arrLyrics[0].replace("%", i + day);
                        System.out.println("\n" + dailyLyric);
                        for (int j = 1; j <= i; j++) {                        	
                        	System.out.println("- " + arrLyrics[j]);
						}    
                        break;
                   case 12:
                        day = "th";
                        dailyLyric = arrLyrics[0].replace("%", i + day);
                        System.out.println("\n" + dailyLyric);
                        for (int j = 1; j <= i; j++) {                        	
                        	System.out.println("- " + arrLyrics[j]);
						}    
                        break;
            }
        }                   		
	}
	
    public static void main(String[] args) 
    {
    	System.out.println("Chương trình xuất ra 12 câu thơ \"The Twelve Days of Christmas.\" \n");
    	XuatTho();
    }
}
Bài 3.18:Design and implement an application that simulates a simple slot machine in which three numbers between 0 and 9 are randomly selected and printed side by side. Print an appropriate statement if all three of the numbers are the same, or if any two of the numbers are the same. Continue playing until the user chooses to stop.(Game Bar)


Code
//---------- Bai 3.18
import java.util.Scanner;
import java.util.Random;
public class Bai3_18 {
	public static void main(String[] args)  
	{
		String answer = "y";
		int num1;
		int num2;
		int num3;
		
		Random generator = new Random(); 
		Scanner scan = new Scanner (System.in); 
		
		System.out.println("Ban co muon choi game Bar nay khong?(y/n): ");
		answer = scan.nextLine();
		
		while(answer.equalsIgnoreCase("y"))
		{
			num1 = generator.nextInt(10); 
		    num2 = generator.nextInt(10);
		    num3 = generator.nextInt(10);
		
		    System.out.println("Ket qua 3 so ngau nhien la: " + num1 + num2 + num3);
		   
		    if(num1 == num2 && num2 == num3)
		    {
		    	System.out.println("JACKPOT! ban da chien thang. oh yeahhhhhhhh....");
		    }
		    
		    if(num1 == num2 || num1 == num3 || num2 == num3 )
		    {
		    	System.out.println("Chi co 2 so giong nhau....huhuuuu");
		    }
		    else
		    {
		    	System.out.println("Ban da thua...huhuuuuuuuuuuuuu");
		    }

		    System.out.print("Ban co muon choi lai khong?(y/n): ");
		    answer = scan.nextLine();
		    System.out.println();
		}
		System.out.println("Bye!!");
	}
}
Bài 3.19:Create a modified version of the  ExamGradesprogram to validate the grades entered to make sure they are in the range 0 to 100, inclusive. Print an error message if a grade is not valid, then contin-ue to collect grades. Continue to use the sentinel value to indicate the end of the input, but do not print an error message when the sentinel value is entered. Do not count an invalid grade or include it as part of the running sum.
Code
//---------- Bai 3.19
//Edit lai bai ExamGrades trang 186
import java.text.DecimalFormat;
import java.util.Scanner;
public class Bai3_19 {
	public static void main(String[] args) {
		
		int grade, count = 0, sum = 0, max, min;
		double average;
		Scanner Keyboard = new Scanner(System.in);  
		System.out.print ("Bạn hãy nhập thứ hạng của Sinh Viên thứ nhất (-1 để thoát): ");
		grade = Keyboard.nextInt();
		max = min = grade;  
		while (grade >= 0)
		{
			if (grade > 100 || grade < 0) {
				System.err.println("\nThứ hạng phải lớn hơn 0 | nhỏ hơn 100");
			}
			else {
				//Đếm số sinh viên
				count++;
				// Tổng kết thứ hạng
				sum += grade;
				// gán MAX và MIN
				if (grade > max)
					max = grade;
									
				if (grade < min)
					min = grade;
			}
			
			System.out.print ("Bạn hãy nhập thứ hạng của Sinh Viên kế tiếp (-1 để thoát): ");
			grade = Keyboard.nextInt ();
		}
		
		//  Thống kế kết quả của SINH VIEN
		if (count == 0)
			System.out.println ("Không có Sinh Viên nên không thể xếp hạng được");
		else
		{
			DecimalFormat fmt = new DecimalFormat ("0.##");
			average = ( double )sum / count;
			System.out.println();
			System.out.println ("Tổng số sinh viên " + count);
			System.out.println ("Thứ hạng trung bình: " + fmt.format(average));
			System.out.println ("Thứ hạng cao nhất là: " + max);
			System.out.println ("Thứ hạng thấp nhât là: " + min);
		}		
	}
}