Hello anh em! Trong hành trình chinh phục LAB211 Java OOP tại FPT, mỗi bài lab đều là một mảnh ghép quan trọng giúp chúng ta nâng cao kỹ năng lập trình. Hôm nay, trên blog TruongDevs, chúng ta sẽ gặp một thử thách tưởng dễ mà lại khiến không ít sinh viên phải "dừng hình" đôi chút: Reverse a String.
Thoạt nghe, bạn có thể nghĩ chỉ đơn giản là đảo ngược chuỗi. Nhưng thực tế, đề bài yêu cầu nhiều hơn thế: chuỗi có thể chứa cả dấu cách lẫn dấu gạch dưới để phân tách từ, đồng thời chương trình phải giữ nguyên trạng thái ký tự hoa, thường và cả ký tự đặc biệt. Chưa hết, ứng dụng còn cần lặp lại nếu người dùng nhấn Enter và chỉ thoát khi bấm ESC. Đây là một bài lab rất hiệu quả để rèn luyện xử lý chuỗi, sử dụng Scanner, vòng lặp và String API trong Java, những kỹ năng cơ bản nhưng cực kỳ quan trọng để bạn tiến xa hơn trên con đường backend Java. Nếu bạn đang theo dõi series LAB211 tại TruongDevs, thì đừng bỏ qua bài tập này nhé

Mục tiêu bài lab Reverse a String (LAB211 FPT)
- Nhập vào một chuỗi ký tự từ bàn phím.
- Thực hiện đảo ngược chuỗi nhưng vẫn giữ nguyên trạng thái chữ hoa, chữ thường và ký tự đặc biệt.
- Hiển thị đầy đủ chuỗi gốc và chuỗi sau khi đảo ra màn hình.
- Chương trình cho phép người dùng lặp lại thao tác khi nhấn Enter hoặc thoát bằng phím ESC.
- Luyện tập cách sử dụng Scanner, vòng lặp và String API trong Java.
Đề bài gốc – Reverse a String (LAB211)
Title:
Reverse a stringBackground Context:
Reverse a stringProgram Specifications:
Create a program allows user input a string from keyboard and then reverse that string.Function details:
1. Enter a string, each word is separated by underscore or space.
2. Reverse the string, keep status of all characters (lower case, upper case, …).
3. Display to the screen the original string and the reversed string.
4. The program continues to do another reverse task if user press Enter key, exit is press Esc.Expectation of User Interface:
Please enter string: My_String Input
The old string: My_String Input
The reversed string: Input String_My
Press enter to continue another reverse, ESC to exitGuidelines
Source Code – Reverse a String (LAB211 FPT)
Dưới đây là full source code project Reverse a String viết bằng Java, bạn có thể copy về chạy trực tiếp trong NetBeans hoặc IntelliJ:
📁 SE1905S02.java
/*
* 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 se1905s02;
import java.util.Scanner;
/**
* S02 - Reverse a string
*
* @author TruongNTCE180140
*/
public class SE1905S02 {
/**
* The main method
*
* @param args the command line arguments
*/
public static void main(String[] args) {
ReverseString handler = new ReverseString();
handler.run();
}
}
📁 ReverseString.java
/*
* 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 se1905s02;
import java.util.Scanner;
/**
* S02 - Reverse a string
*
* @author TruongNTCE180140
*/
public class ReverseString {
String input = ""; // Variable to store the input string from the user
StringBuilder reversed = new StringBuilder(); // StringBuilder for efficient string manipulation
/**
* Main method to run the program. This method runs in an infinite loop
* until the user enters 'quit'. After each input, the string will be
* reversed, and the result will be displayed.
*/
public void run() {
Scanner scanner = new Scanner(System.in); // Create a Scanner object to get user input
while (true) { // Infinite loop, will continue until the user inputs 'quit'
System.out.print("Please enter string: ");
input = scanner.nextLine().trim(); // Read the input string from the user
// If the user enters 'quit', exit the program
if (input.equalsIgnoreCase("quit")) {
break; // Exit the loop and end the program
}
// Validate input: it must contain at least one letter and can include numbers, underscores, and spaces
if (!isValidInput(input)) {
System.out.println("Input must contain at least one letter, and can only contain letters, numbers, underscores, and spaces. Please enter a valid string.");
continue; // Invalid input, ask the user again
}
// Call the method to print the original and reversed strings
print();
// Prompt the user whether they want to continue or exit
while (true) {
System.out.print("Press Enter to continue or type 'quit' to exit: ");
String choice = scanner.nextLine().trim(); // Read the user's choice
// If the user enters 'quit' (case-insensitive), exit the program
if (choice.equalsIgnoreCase("quit")) {
return; // Exit the main method and terminate the program
}
// If the user presses Enter, continue
if (choice.isEmpty()) {
break; // Break out of the inner loop and continue to the next iteration
}
// If the input is invalid, prompt again
System.out.println("Invalid input. Press Enter to continue or type 'quit' to exit.");
}
}
}
/**
* Checks whether the input is valid. The input must contain at least one
* letter and can contain numbers, underscores, and spaces.
*
* @param input the string entered by the user
* @return true if the input is valid, false otherwise
*/
public boolean isValidInput(String input) {
// Check if the input contains at least one letter (a-z or A-Z)
return input.matches(".*[a-zA-Z]+.*") && input.matches("[a-zA-Z\\d_ ]+");
}
/**
* Reverses the input string while preserving the positions of separators
* (spaces, underscores, and hyphens) and displays the reversed string.
*
* @param input the original string input from the user
*/
public void reverseAndDisplay(String input) {
// Split the input string into words, keeping the separators (spaces, underscores, hyphens)
String[] words = input.split("(?=[ _-])|(?<=[ _-])");
// Clear previous content in StringBuilder 'reversed' to reset it before appending new content
reversed.setLength(0);
// Loop through the array of words and separators in reverse order and append each element to the 'reversed' StringBuilder
for (int i = words.length - 1; i >= 0; i--) {
reversed.append(words[i]);
}
}
/**
* Prints the original and reversed string.
*/
public void print() {
// Call the method to reverse the input string
reverseAndDisplay(input);
// Print the original string
System.out.println("The original string: " + input);
// Print the reversed string
System.out.println("The reversed string: " + reversed.toString());
}
}
Ngoài bài Reverse a String, trong series LAB211 Java OOP trên TruongDevs bạn có thể tham khảo thêm:
Giải Bài Insert New Element Into Sorted Array – Java OOP (LAB211 – FPT)
Giải Bài Candidate Management System – Java OOP (LAB211 – FPT)
Kết luận
Bài lab Reverse a String LAB211 FPT tuy đơn giản nhưng lại giúp bạn rèn luyện kỹ năng xử lý chuỗi, sử dụng Scanner, vòng lặp và các thao tác cơ bản với String API trong Java. Đây cũng là nền tảng quan trọng để làm những bài nâng cao hơn như kiểm tra chuỗi Palindrome, xử lý Regex hay quản lý dữ liệu văn bản.
Nếu bạn đang theo học LAB211 Java OOP tại FPT hoặc muốn tự luyện code, hãy lưu lại project này để ôn tập. Đừng quên theo dõi series tại TruongDevs để xem thêm nhiều bài giải lab kèm source code chi tiết nhé
Cam kết uy tín - đúng deadline - bảo mật tuyệt đối.
Liên hệ: Zalo.me/0973898830