Java 仅仅为了可读性而创建常量变量可以吗?

Java 仅仅为了可读性而创建常量变量可以吗?,java,coding-style,Java,Coding Style,想象一下,如果我有这段代码: System.out.println("Is the product:\n"+ "1. National.\n"+ "2. International."); int choice = input.nextInt(System.in); if (choice == 1) (...) else if (choice == 2) (...) 那么,这样做可以吗 final

想象一下,如果我有这段代码:

System.out.println("Is the product:\n"+
                    "1. National.\n"+
                    "2. International.");
int choice = input.nextInt(System.in);
if (choice == 1)
    (...)
else if (choice == 2)
    (...)
那么,这样做可以吗

final int NATIONAL = 1;
final int INTERNATIONAL = 2;
System.out.println("Is the product:\n"+
                        "1. National.\n"+
                        "2. International.");
int choice = input.nextInt(System.in);
if (choice == NATIONAL)
    (...)
else if (choice == INTERNATIONAL)
    (...)

我不知道,我刚买了鲍勃叔叔写的干净的代码书,我开始质疑自己

我相信常数比魔法数字好。
使用常量,您可以在一个位置控制定义并更好地命名。这将影响代码的进一步可维护性。
在某些情况下,尝试使用
enum
而不是常量<代码>枚举比常量有更多优点。
在这种情况下,枚举示例类似于以下代码:

enum用户输入{
国家(1)、国际(2)、未知(-1);
私有int输入;
公共int getInput(){
返回输入;
}
用户输入(INTI){
这个输入=i;
}
公共静态用户输入getUserInput(int输入){
for(UserInput UserInput:UserInput.values()){
if(userInput.getInput()==input){
返回用户输入;
}
}
返回未知;
}
}
//主要
公共静态void main(字符串[]args){
System.out.println(“是产品:\n”+
“1.全国性。\n”+
“2.国际。”);
扫描仪sc=新的扫描仪(System.in);
int choice=sc.nextInt();
开关(UserInput.getUserInput(选项)){
国家案例:突破;
案例国际:突破;
违约:
}
}

检查更多信息:

当您想要对一些变量(常量)或代码进行多重编码时,您可以创建常量以更好地可读性和理解。 例如-: 如果(选项==国家) (...) else if(选项==国际) (……)


当您必须多次使用国际和国家标准时是正确的

为什么会不好?在我看来,这取决于上下文。在你的例子中,它是完美的。如果你有37像素的边距,我会感到困惑。好吧,IDK,如果它消耗更多的内存或其他什么的话。是的,没问题。事实上,很多人都推荐这一做法。我决定使用常量,因为如果存在用户的输入,我真的不知道如何使用枚举。@Sebastianarrita,在本例中,我使用枚举示例更新代码。我希望它能帮助您学习
enum
。它在Java中非常有用。