如何实现字符串框式展示?Java代码调试求助
Hey there! Let's get that boxed string effect working properly. First, let's break down the gaps in your existing code snippet, then walk through a complete, working solution.
What's Missing in Your Current Code
From the snippet you shared, your code cuts off mid-for-loop, and you’re overcomplicating things with the SidePhrase variable. The core logic for drawing the box’s top/bottom borders and proper side framing around your string is missing entirely. Also, quick note: Java conventions use lower camel case for variable names (e.g., phrase instead of Phrase) to keep code consistent and readable.
Complete Working Code
Here’s a polished version that creates a clean, properly formatted box around your input string:
import java.util.Scanner; public class StringInABox { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Enter a phrase or word!"); String phrase = scan.nextLine(); String capPhrase = phrase.toUpperCase(); int phraseLength = capPhrase.length(); // Draw top border: + followed by dashes, then + System.out.print("+"); for (int i = 0; i < phraseLength + 2; i++) { System.out.print("-"); } System.out.println("+"); // Draw middle line with the string wrapped in borders System.out.println("| " + capPhrase + " |"); // Draw bottom border (matches the top border) System.out.print("+"); for (int i = 0; i < phraseLength + 2; i++) { System.out.print("-"); } System.out.println("+"); scan.close(); // Clean up the scanner resource } }
How It Works
- Top/Bottom Borders: We start with a
+, then add enough dashes to cover the string length plus 2 (for the padding spaces around the string), then end with another+to cap the border. - Middle Line: The uppercase string is wrapped in
|and|to create side borders with consistent padding, making the box look neat and balanced. - Scanner Cleanup: Closing the
Scanneris a good practice to avoid unnecessary resource leaks in Java.
Example Output
If you input "Hello World", you’ll get this clean boxed result:
+--------------+ | HELLO WORLD | +--------------+
内容的提问来源于stack exchange,提问作者S. West

