Bài tập & code Java (Sưu tầm và update thường xuyên)

**Rico**

Mr & Ms Pac-Man
Chả là tớ muốn tạo 1 nơi để lưu giữ các code, lời giải các bài tập Java đó mà...
Những bài tập sưu tầm và update, thứ nhất là lấy nơi để xem lại code bài tập, thứ hai là giúp được anh em nào thì thật là tốt :>.

Tất cả sẽ bắt đầu từ những bài cơ bản nhất, dễ nhất...

Chú ý 1 chút là tớ gói(package) và lớp(class) chính tớ sẽ đặt tên tượng trưng thôi nhé.
.
___________Auto Merge________________


list bài tập sẽ dựng lại sau.tạm thời up dần dần lên.


-----------------------------------------------------------------------------------------------------------------------------------------------

1.

a)Hãy viết một đoạn chương trình để xuất dòng chữ :” Welcome to the world of Java”


PHP:
package test;

public class Test{
 public static void main(String[] args) {
        System.out.println("Welcome to the world of JAVA !!!");
      }  
    }


b)Nhập 2 số a và b, in ra màn hình kết quả tổng của a và b:

PHP:
package Test;
import java.util.*;

public class Test {

    public static void main(String[] args) {
        System.out.print("Nhap vao so a : ");
        Scanner input=new Scanner(System.in);
        int a=input.nextInt();
        System.out.print("Nhap vao so b : ");
        Scanner input2=new Scanner(System.in);
        int b=input2.nextInt();
        int c=a+b;
        System.out.println("Tong 2 so a va b la : "+c);
         }
}

-----------------------------------------------------------------------------------------------------------------------------------------------


2. Hãy viết hai hàm kiến tạo mở (explicit) cho một lớp dùng để tính diện tích hình chữ nhật.Khi một giá trị đơn được truyền vào hàm khởi tạo,nó có thể bị ngộ nhận rằng độ dài và chiều cao giống như biến được truyền vào.Lúc đó, nó sẽ tính một diện tích phù hợp.Khi hai giá trị được truyền vào hàm,nó sẽ tính diện tích hình chữ nhật.

PHP:
package test;

public class Rectangle { //hinh chu nhat 
    private int length; //chieu cao
    private int width; //chieu rong

    Rectangle(int a,int b){
        this.length=a;
        this.width=b;}

    Rectangle(int a){
        this.length=a;
        this.width=a;}
    
int areaCalculation(){ //phuong thuc(ham) tinh dien tich
        return length*width;
    }

    public static void main(String[] args) {
        Rectangle rec1=new Rectangle(10);
        int result1=rec1.areaCalculation();
        System.out.println(result1);

        Rectangle rec2=new Rectangle(15,12);
        int result2=rec2.areaCalculation();
        System.out.println(result2);
}
}
 
3.Viết một chương trình hiển thị tổng các bội số của 7 nằm giữa 1 và 100.

PHP:
package test;

public class Test {

public static void main(String[] args) {
        int i,sum=0;
        for(i=7;i<100;i++){
            if(i%7==0)
                sum+=i;
             }
             System.out.println("Sum of the multiples of 7 between 1 and 100 is "+sum);
        //tong cac boi so cua 7 nam giua 1 va 100
         }
}
 
PHP:
package test;

public class Test {

public static void main(String[] args) {
        int i=7,sum=0;
       while(i<100){
           if(i%7==0){
               sum+=i;
           }
           i++;
           }
System.out.println("Sum of the multiples of 7 between 1 and 100 is "+sum);
        //tong cac boi so cua 7 nam giua 1 va 100
         }
}
 
4.Viết chương trình để cộng bảy số hạng của dãy sau : 1!+2!+3!…………….


PHP:
package test;

public class Test {

public static void main(String[] args) {
     /** Viết chương trình để cộng bảy số hạng của dãy sau:
/*1!+2!+3!………*/
        
       int i,product=1,sum=0;
       for(i=1;i<=7;i++){
           product*=i;
           sum+=product;
       }
       System.out.println("Sum from 1! to 7! is "+sum);
       //Tổng của các giai thừa của 1 đến 7
    }
}
 
5.Viết chương trình tính giá trị biểu thức (giá trị n nhập từ bàn phím):

A=1+1/2!+1/3!+..+1/n!

PHP:
import java.util.*;

public class Test (

public static void main(String[] args) {
     /**
	Viết chương trình tính giá trị biểu thức (giá trị n nhập từ bàn phím):
A=1+1/2!+1/3!+..+1/n!*/

System.out.print("Nhap so vao ban phim : ");
    Scanner input=new Scanner(System.in);
        float n=input.nextInt();
        float i,product=1;
        float sum = 0;
     for(i=1;i<=n;i++)
        { product*=i;
         sum+=(1/product); }
 System.out.println("A= "+sum);
        }
}
 
6. Viết chương trình yêu cầu người dùng nhập vào một số tự nhiên . Thực hiện kiểm tra số
nhập vào là chẵn hay lẻ .

PHP:
package Test;
import java.util.*;

public class Test {
    /**Viết chương trình yêu cầu người dùng nhập vào một số tự nhiên . Thực hiện kiểm tra số
nhập vào là chẵn hay lẻ .*/

    public static void main(String[] args) {
        System.out.print("Nhap vao 1 so tu nhien : ");
        Scanner input=new Scanner(System.in);
        int a=input.nextInt();
        if(a%2==0){
            System.out.println("So vua nhap la so chan !!");
        }
        if(a%2!=0){
            System.out.println("So vua nhap la so le !!");
        }
                }
}
 
7.Viết chương trình in ra màn hình các mẫu sau :


a)

*
**
***
****
*****
******
*******
********
*********
**********

PHP:
package Test;

public class Test {
    public static void main(String[] args) {
       int i,j;
        for(i=0;i<10;i++){
             
            for(j=0;j<=i;j++){
                System.out.print("*");
            }
          System.out.print("\n");
         }
}
}


b)

**********
*********
********
*******
******
*****
****
***
**
*

PHP:
package Test;

public class Test {
    public static void main(String[] args) {
       int i,j;
        for(i=0;i<10;i++){
             
            for(j=10;j>i;j--){
                System.out.print("*");
            }
          System.out.print("\n");
         }
}
}


c)

**********
*********
********
*******
******
*****
****
***
**
*
PHP:
package Test;

public class Test {
    
    public static void main(String[] args) {
       int i,j,k;
       for(i=0;i<10;i++){
           for(k=0;k<i;k++){
               System.out.print(" ");
           }
           for(j=10;j>i;j--){
               System.out.print("*");
           }
           System.out.println();
       }
    }
}



d)

*
**
***
****
*****
******
*******
********
*********
**********

PHP:
package Test;

public class Test {
    
    public static void main(String[] args) {
       int i,j,k;
       for(i=0;i<10;i++){
           for(k=9;k>i;k--){
               System.out.print(" ");
           }
           for(j=0;j<=i;j++){
               System.out.print("*");
           }
           System.out.println();
       }
    }
}
 
8.In tất cả các số từ 0 đến 10 , trừ 3 số 3,4,5.

PHP:
package Test;

public class Test {
/** In tat ca cac so tu 0 den 10, bo qua 3,4,5.
 *
 *
 */
   public static void main(String[] args) {
        int i;
        for(i=0;i<=10;i++){
            if((i==3)||(i==4)||(i==5)) continue;
                System.out.println(i);
             }
    }
}
 
*Create a Rectangle class to allow to enter 2 whole numbers from the keyboard then print the area and parimeter

PHP:
package test;
import java.util.*;
/**
 *
 * @author Rico
 */
public class Rectangle {
  /**
     * Create a Rectangle class to allow to enter 2 whole numbers from the keyboard then print the area and parimeter
     */
    public static void main(String[] args) {
        System.out.println("Please enter two edges of the rectangle !!!!");
 Scanner sc=new Scanner(System.in);
       System.out.println("Width : ");
       int a=sc.nextInt();
       System.out.println("Height : ");
       int b=sc.nextInt();
       System.out.println("The area is : "+a*b);
       System.out.println("The perimeter is : "+(a+b)*2);
      }
    }



p/s: bối bối : tớ muốn lưu vào đây làm nơi lưu trữ ý mà, bạn nào mới học vào cũng đc,sẽ update dần dần, thật nhiều,ko biết ý kiến mod box ra sao,tớ cứ làm đã...
 
Mã:
        if(a%2==0){
            System.out.println("So vua nhap la so chan !!");
        }
        if(a%2!=0){
            System.out.println("So vua nhap la so le !!");
        }
dùng if else cho nó tiện đi bạn :|
 
tai liệu của bạn rất có ích cho mình. rất cảm ơn bạn. mong bạn luôn thành công trong cuốc sống.
 
Creating a Rect with 2 properties are width and height

- method void input() to enter the value for width and height from the keyboard

- method void displayArea() to print the area

- In main method, create an object and call these above method to print the data


PHP:
import java.util.*;

public class Rect {
  int width,height;
    void input(){
        System.out.println("Please enter width and height : ");
        Scanner sc=new Scanner(System.in);
        width=sc.nextInt();
        height=sc.nextInt();
    }
    void displayArea(){
        System.out.println("The Area is: "+width*height);
    }
    
      public static void main(String[] args) {
       Rect rect=new Rect();
       rect.input();
       rect.displayArea();
     }
    }
 
Creating class Student with properties are name, age, math, literature

- method void input() to enter the data from the keyboard

- float getResult() to return the result, with result = (math*2 + literature)/3

- In main method, create the Student object and call the above method to print the data


PHP:
import java.util.*;
public class Student {
String name;
int age;
float math,literature;
void input(){
      Scanner sc=new Scanner(System.in);
    System.out.println("Please enter information of student : ");
    System.out.print("Name: ");
    name=sc.next();
    System.out.print("Age: ");
    age=sc.nextInt();
     System.out.print("Math : ");
     math=sc.nextFloat();
     System.out.print("Literature: ");
     literature=sc.nextFloat();
}
float getResult(){
     return (math*2+literature)/3;
}
public static void main(String[] args) {
      Student st=new Student();
      st.input();
      System.out.println(" The result is: "+st.getResult());
      }
   }
 
Creating class ATM with properties accID, balance, amount
- method voidinput() to enter the value of balance and accID
- method void withdraw() to allow enter the value of amount (amount <= balance), then compute balance = balance – amount
- method void displayBalance() to print the balance
- In main method, creating the ATM object and call the above method

PHP:
import java.util.Scanner;

public class ATM{
int accID;
float balance,amount;

void input(){
    Scanner sc=new Scanner(System.in);
    System.out.println("Please enter the information of account!!");
    System.out.println(" Account ID : ");
    accID=sc.nextInt();
    System.out.println(" Balance : ");
    balance=sc.nextFloat();
     }
void withdraw(){
    Scanner sc=new Scanner(System.in);
    do{
        System.out.println(" Amount<=Balance !!!");
        amount=sc.nextFloat();
    }while(amount>balance);
    balance=balance-amount;
}
void displayBalance(){
    System.out.println(" Your balance now is : "+balance);
}
    public static void main(String[] args) {
        ATM account=new ATM();
        account.input();
        account.withdraw();
        account.displayBalance();
          }
}
 
Class Product with properties are ID – int, Name – String, quantity – int, Price – float
Methods are:
- void createProduct() : enter the information of product from the keyboard
- void displayProduct() : display product’s information as format:
id name quantity price cost
float getCost() : return the cost for a product (price * quantity)
- void sortProduct(Product p[]) : sort product in array p base on cost (price * quantity) in acsending
- Product findProduct(int quantity, Product p[]) : return the first product that has the quantity is greater than the number you have entered.
- In main:
+ Create an array product with n elements, n is get from the keyboard
+ Enter the information for all elements of array p
+ Display all products in ascending of cost
+ Enter a whole number from the keyboard, display the information of the first product that has the quantity is greater than this number.

PHP:
import java.util.*;
public class Product {
int id,quantity;
String name;
float price;
void createProduct(){
    Scanner sc=new Scanner(System.in);
    System.out.println("Enter the information of product from the keyboard : ");
    System.out.print(" ID: ");
    id=sc.nextInt();
    System.out.print(" Quantity: ");
    quantity=sc.nextInt();
    System.out.print(" Name: ");
    name=sc.next();
    System.out.print(" Price: ");
    price=sc.nextInt();

}
float getCost(){
    return quantity*price;
}
void displayProduct(){
    System.out.println(id+"\t\t "+name+"\t\t "+quantity+"\t\t  "+price+"\t\t  "+getCost());
}

void sortProduct(Product p[]){
        Product temp = new Product();
        for(int i = 0; i < p.length; i++){
            for(int j = i + 1; j < p.length; j++){
                if(p[j].getCost() < p[i].getCost()){
                    temp = p[i];
                    p[i] = p[j];
                    p[j] = temp;
                }
            }
        }
    }
EvenSum findProduct(int inQuantity, Product p[]){
        Scanner find = new Scanner(System.in);
        inQuantity = find.nextInt();
        System.out.printf("The first product is greater than %d is: ", inQuantity);
        for(int i = 0; i < p.length; i++){
            if(inQuantity == p[i].quantity){
                return p[i];
            }
        }
        return null;
    }

  public static void main(String[] args) {
   int i;
        Scanner s = new Scanner(System.in);
        System.out.println("Please enter the number of product: ");
        int n = s.nextInt();
        Product[] p = new Product[n];

        for(i = 0; i < n; i++){
            p[i] = new Product();
            p[i].createProduct();
        }
        System.out.println("Id\t\tname\t\tquantity\t\tprice\t\tcost");
        for(i = 0; i < n; i++){
            p[i].sortProduct(p);
            p[i].displayProduct();
        }
}
}
 
Class EvenSum to do:
- Enter 2 number a and b, a and b must be great than or equal to 5
- Display the sum of all even numbers from a to b

PHP:
import java.util.*;
public class EvenSum {
    int a,b,sum=0;
    void input(){
        Scanner sc=new Scanner(System.in);
        do{
        System.out.println("Please enter number 1: ");
        a=sc.nextInt();
        System.out.println("Please enter number 2: ");
        b=sc.nextInt();
    }while(a<5||b<5);
    }
void exchangeNumbers(){
        if(a>b){
            int temp=a;
            a=b;
            b=temp;
        }
    }
void displaySum(){
        for(int i=a;i<=b;i++){
            if(i%2==0){
               sum+=i;}
        }
        System.out.print(" Rico: "+sum+"\n");
    }
public static void main(String[] args) {
   EvenSum calSum=new EvenSum();
   calSum.input();
   calSum.exchangeNumbers();
       calSum.displaySum();
}
}
 
Build the ATM application that consists below classes:
a. Class Account with properties are id – int, name – String, balance – int
Method in Account class:
- int getBalance() : return the balance
- void createAcc() : to enter the information of account from the keyboard
- boolean withdraw(int amount) : get money from the account, if amount > balance, the transaction is not successful, else balance = balance – amount
- boolean transfer(Account a, int amount) : transfer money to account a. If amount > balance, transaction is not successful, balance -= amount and balance of a += amount
- boolean deposit(int amount) : offer money to account. If amount > 0, balance += amount
b. Class AccountTest with main() to do:
- declare account a and b, then enter the information for 2 accounts
- Enter a number to represent an id of account. If this number is id of a or b, then display the menu below functions, else print the message “Please enter the correct id”
1 : Get the balance
2 : withdraw an amount that get from the keyboard
3 : transfer money an amount. If the current account is a then transfer to b and vice versal
4 : Offer money to account
5 : End
The menu will display again after performing one transaction.

Class Account.java:

PHP:
import java.util.Scanner;
public class Account {
   int id;
   String name;
   int balance;

   public Account(){
      createAcc();
   }

   int getBalance(){

      return  balance;
   }

   void createAcc(){
      Scanner sc = new Scanner(System.in);
      System.out.print("Enter id of account: ");
      id = sc.nextInt();
      System.out.print("Enter name of account: ");
      name = sc.next();
      System.out.print("Enter balance of account: ");
      balance = sc.nextInt();

   }
   boolean withdraw(int amount){
      boolean temp = false;
      if(amount > balance)
      {
         temp = false;
      }
      else{
         balance -= amount;
         temp = true;
      }

      return temp;
   }

   boolean transfer(Account a, int amount){
      boolean temp = false;
      if(amount > balance)
      {
         temp = false;
      }
      else{
         balance -= amount;
         a.balance += amount;
         temp = true;
      }
      return temp;
   }

   boolean deposit(int amount){
      boolean temp = false;
      if(amount > 0)
      {
         balance += amount;
         temp = true;
      }
      else{
         temp = false;
      }

      return temp;
   }

   //void displayImfo(){
   //   System.out.println("---Imformation of account---");
   //   System.out.println("Id of account: " + id);
   //   System.out.println("Name of account: " + name);
   //   System.out.println("Balance of account: " + balance);
   //}
}


Class AccountTest.java:

PHP:
import java.util.Scanner;
public class AccountTest {

    public static void main(String[] args) {
       AccountTest at = new AccountTest();
       boolean ok = false;
       Account a, b;
       a = new Account();
       b = new Account();
      Scanner sc = new Scanner(System.in);

      do{
         System.out.println("--------ATM--------");
         System.out.print("Please enter your id number: ");
         int vid = sc.nextInt();
          if(vid == a.id)
          {
             at.displayMenu(a, b);
             ok = true;
             }
             else
                if(vid == b.id){
                   at.displayMenu(b, a);
                   ok = true;
                }
                else{
                   ok = false;
                   System.out.println("Please enter the correct id");
                }
      }while(!ok);


    }
    void displayMenu(Account a, Account b){
       int selection;
       Scanner sc = new Scanner(System.in);
       while(true)
       {
          System.out.println("---ATM---");
          System.out.println("1. Get the balance");
          System.out.println("2. Withdraw an amount that get from the keyboard");
          System.out.println("3. Transfer money an amount");
          System.out.println("4. Offer money to account");
          System.out.println("5. End");
          System.out.println("-------------------");
          System.out.print("Your choice: ");
          selection = sc.nextInt();
          selectionFunction(a, b, selection);

       }

    }

    void selectionFunction(Account a, Account b, int selection){
       Scanner sc = new Scanner(System.in);
       int amount;
       switch(selection){
          case 1:{   System.out.println("Your balance is : "+ a.getBalance());
                  break;
          }
          case 2: {   System.out.print("Enter amount you want withdraw: ");
                   amount = sc.nextInt();
                   if(a.withdraw(amount)){
                      System.out.println("You withdraw successful!. Amount = "+ amount + ". Your balance have : "+ a.getBalance());
                   }
                   else{
                      System.out.println("The transaction is not successful!");
                   }
                   break;
          }
          case 3: {   System.out.print("Enter amount you want transfer: ");
                   amount = sc.nextInt();
                   if(a.transfer(b, amount)){
                      System.out.println("You transfer to account "+ b.name + " successful!, with  Amount = "+ amount +". Your balance have : "+ a.getBalance());
                   }
                   else{
                      System.out.println("The transaction is not successful!");
                   }
                   break;
          }
          case 4: {   System.out.print("Enter amount you want offer to your account: ");
                   amount = sc.nextInt();
                   if(a.deposit(amount)){
                      System.out.println("The transaction is successful!. Now your balance is: " +a.getBalance() );
                   }
                   else{
                      System.out.println("The transaction is not successful!");
                   }
                   break;
          }
          case 5: {   System.out.println("Thank you use ATM!");
                   System.exit(1);
                   break;
          }
          default: {   System.out.println("your choice wrong! Please choice again!");
             }

       }

    }

}
 
Back
Top