java编程问题,把用户输入的字符串分行并加入空格..

如图, 需要把用户输入的 if-then-else语句分行并加入空格,从而更容易阅读..求救啊 !一点主意都没有..

以下解答供题主参考,应该还会有更高效的方法。

import java.util.Scanner;

public class Reformat {

    public static void main(String[] args) {

        String result;

        System.out.println("Enter your if-then-else statement and press Enter: ");

        // 获得用户输入
        Scanner scanner  = new Scanner(System.in);
        String rawInput = scanner.nextLine();

        // 将用户输入按 if 和 else 分开,split("if|else") 代表以 if 和 else 作为
        // 关键字分割字符串
        String[] splitedStatement = rawInput.trim().split("if|else");

        // 从 split() 返回的数组中分别提取 if 和 else 语句中的内容。如果没有 else 语句,
        // 将其标记为 null。(因为 if 关键字总在用户输入的开头,而 split() 方法遇到位于
        // 字符串开头的分隔符时会在返回的数组中的第一个位置添加一个空字符串,所以这里的
        // index 从 1 开始而不是 0,因为 splitedStatement[0] 总是一个空字符串)
        String ifStatement = splitedStatement[1];
        String elseStatement = splitedStatement.length > 2 ? 
                                splitedStatement[2] : null;

        // 从得到的 if 语句中分别抽出其条件和内容,split("\\{|\\}") 代表以 { 和 } 作为
        // 关键字分割字符串
        String ifCondition = ifStatement.split("\\{|\\}")[0].trim();
        String ifContent = ifStatement.split("\\{|\\}")[1].trim();

        // 重新将上面两个字符串组成格式化后的 if 语句
        String ifResult = "if " + ifCondition +
                            " {\n\t" + ifContent + "\n}";

        // else 语句同理,只不过需要先判断其是否存在,从而避免 NullPointerException
        if (elseStatement != null) {
            String elseCondition = elseStatement.split("\\{|\\}")[0].trim();
            String elseContent = elseStatement.split("\\{|\\}")[1].trim();
            String elseResult = "\nelse" +
                                elseCondition +
                                " {\n\t" + elseContent + "\n}";

            // 将格式化后的 if 和 else 语句组成最终结果
            result = ifResult + elseResult;
        } else {
            // 如果 else 不存在,那么 if 语句就是最终结果
            result = ifResult;
        }

        // 输出结果
        System.out.println("\nReformatted result: \n\n" + result);

    }
}


if 和 else 都存在的运行结果:



没有 else 语句的运行结果:


温馨提示:答案为网友推荐,仅供参考
第1个回答  2016-09-28
eclipse里 : ctrl+shift+f
相似回答