Java 如何让eclipse自动为IF语句添加大括号?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3704308/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 03:41:32  来源:igfitidea点击:

How to make eclipse automatically add braces to an IF statement?

javaeclipsecurly-braces

提问by Bromide

In Java the following is completely valid:

在 Java 中,以下内容完全有效:

if (x == null)
    Y();
else
    Z();

I personally don't like it at all. I like all my IF statements to have braces:

我个人一点也不喜欢。我喜欢我所有的 IF 语句都有大括号:

if (x == null) {
    Y();
} else {
    Z();
}

The eclipse formatter is wonderful and can beautify my code in many other ways.

eclipse 格式化程序非常棒,可以在许多其他方面美化我的代码。

Is there a way to have it add the braces to IF statements?

有没有办法让它在 IF 语句中添加大括号?

采纳答案by gk5885

Under "Preferences": Java > Editor > Save Actions

在“首选项”下:Java > 编辑器 > 保存操作

1) Check "Additional actions"

1) 勾选“其他操作”

2) Click "Configure…"

2)点击“配置...”

3) Go to the "Code Style" tab

3)转到“代码样式”选项卡

4) Check "Use blocks in if/while/for/do statements" and configure to your preferences

4) 选中“在 if/while/for/do 语句中使用块”并根据您的喜好进行配置

回答by ChrisH

Yes.

是的。

Eclipse menu: Source -> Clean Up...

Eclipse 菜单:源 -> 清理...

Configure... -> Code Style -> Use blocks in if/while/for/do statements.

配置... -> 代码风格 -> 在 if/while/for/do 语句中使用块。

回答by Ayusman

I usually do it by creating a code formatter by copying the built in eclipse formatter, here:

我通常通过复制内置的 Eclipse 格式化程序来创建代码格式化程序,在这里:

Windows > Preferences > Java > Code Style > Formatter 

Select the profile that you have just created. and click on Edit and go to "Braces" tab.

选择您刚刚创建的配置文件。并单击“编辑”并转到“大括号”选项卡。

Change the braces placement as you like (it's a WYSIWYG kind of editor, makes it easy) .

根据需要更改大括号的位置(这是一种所见即所得的编辑器,很容易)。

When I need to format, I just select all the text and Ctrl+Shift+Fand it works fine for me.

当我需要格式化时,我只需选择所有文本Ctrl+Shift+F,它对我来说效果很好。

回答by Peter

This is what I did: Eclipse -Preferences-Java-Code Style-Formatter-Edit-Braces Select next line as desired in each box then save as a different name (your choice).

这就是我所做的: Eclipse -Preferences-Java-Code Style-Formatter-Edit-Braces 根据需要在每个框中选择下一行,然后另存为不同的名称(您的选择)。

回答by user1050755

In Eclipse Oxygen (2017+), that option is now at:

在 Eclipse Oxygen (2017+) 中,该选项现在位于:

Window -> Preferences -> Java -> Code Style -> Clean Up -> Edit -> second tab "Code Style"

Window -> Preferences -> Java -> Code Style -> Clean Up -> Edit -> second tab "Code Style"

After changing, select the corresponding parts of your code and run the "Clean Up" option.

更改后,选择代码的相应部分并运行“清理”选项。