声明这些变量的风格最正确的方法是什么?

时间:2015-09-30 04:23:02

标签: java initialization

我对计算机科学有些陌生,我编写了一个使用大量变量的项目。我拥有main方法中的所有代码,并且在main方法的开头,我已经声明了大部分变量。我觉得这很难看。我不想改变我的整个代码并弄乱范围。有没有办法声明这些相同的变量,让它看起来更有效/专业?

int numPlain;
int numPepperoni;
int pizzasOrdered = 0;
int slicesOrdered = 0;
int charmsOrdered = 0;
int totalSlices = 0;
int totalCharms = 0;
int totalPlain = 0;
int totalPepperoni = 0;
double plainCost = 0.0;
double pepperoniCost = 0.0;
double sliceCost = 0.0;
double pieCost = 0.0;
double charmCost = 0.0;
boolean flag = true;
double totalCost = 0.00;
double paymentAmt = 0.0;
int numPies = 0;

2 个答案:

答案 0 :(得分:2)

可以尝试内联一些变量声明/初始化,如下所示:

int numPlain, numPepperoni;
int pizzasOrdered = 0, slicesOrdered = 0, charmsOrdered = 0;
int totalSlices = 0, totalCharms = 0, totalPlain = 0, totalPepperoni = 0;
double plainCost = 0.0, pepperoniCost = 0.0, sliceCost = 0.0, pieCost = 0.0, charmCost = 0.0;
boolean flag = true;
double totalCost = 0.00;
double paymentAmt = 0.0;
int numPies = 0;

这会使代码看起来不那么冗长,并且还会将彼此相关的变量组合在一起。

答案 1 :(得分:0)

我的老大学教授总是这样说:

int     numPlain;
int     numPepperoni;
int     pizzasOrdered   = 0;
int     slicesOrdered   = 0;
int     charmsOrdered   = 0;
int     totalSlices     = 0;
int     totalCharms     = 0;
int     totalPlain      = 0;
int     totalPepperoni  = 0;

double  plainCost       = 0.0;
double  pepperoniCost   = 0.0;
double  sliceCost       = 0.0;
double  pieCost         = 0.0;
double  charmCost       = 0.0;

boolean flag            = true;

double  totalCost       = 0.00;
double  paymentAmt      = 0.0;

int     numPies         = 0;

这真的是所有的偏好。主要关键是可读性。随着您的进步,您在单个函数中也不会有尽可能多的原始变量。

编辑另请注意,您可以按类型或相关性(按功能将变量分组)将变量分组在一起