You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现字符串框式展示?Java代码调试求助

Fixing Your Java String-in-a-Box Implementation

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 Scanner is 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:08:39