Java 压缩代码行
如果我有下面几行代码,有没有办法把它压缩成1行或2行,然后使用循环或类似的东西?有100多个索引,因此需要写出大量文本Java 压缩代码行,java,optimization,indexing,Java,Optimization,Indexing,如果我有下面几行代码,有没有办法把它压缩成1行或2行,然后使用循环或类似的东西?有100多个索引,因此需要写出大量文本 unrlzdPnl = (((Positions[0].GetProfitLoss(Closes[0][0], PerformanceUnit.Points))*200) + ((Positions[1].GetProfitLoss(Closes[1][0], PerformanceUnit.Points))*200) + ((Positions[2].GetProfitLo
unrlzdPnl =
(((Positions[0].GetProfitLoss(Closes[0][0], PerformanceUnit.Points))*200)
+ ((Positions[1].GetProfitLoss(Closes[1][0], PerformanceUnit.Points))*200)
+ ((Positions[2].GetProfitLoss(Closes[2][0], PerformanceUnit.Points))*200)
+ ((Positions[3].GetProfitLoss(Closes[3][0], PerformanceUnit.Points))*200)
+ ((Positions[4].GetProfitLoss(Closes[4][0], PerformanceUnit.Points))*200)
+ ((Positions[5].GetProfitLoss(Closes[5][0], PerformanceUnit.Points))*200)
+ ((Positions[6].GetProfitLoss(Closes[6][0], PerformanceUnit.Points))*200)
);
也许我不明白,但我会说:
int unrlzPnl = 0;
for (int i = 0; i < nb_indices; i++) {
unrlzdPnl += Positions[i].GetProfitLoss(Closes[i][0],
PerformanceUnit.Points);
}
unrlzPnl *= 200;
编辑#2: 好的,如果您真的希望它尽可能紧凑,并且避免每次调用函数时初始化:
int MyFunction(int nb_indices) {
if (1 > nb_indices)
return 0;
unrlzdPnl = Positions[0].GetProfitLoss(Closes[0][0],
PerformanceUnit.Points);
for (int i = 1; i < nb_indices; i++)
unrlzdPnl += Positions[i].GetProfitLoss(Closes[i][0],
PerformanceUnit.Points);
return unrlzPnl * 200;
}
int MyFunction(int nb_索引){
如果(1>nb_指数)
返回0;
unrlzdPnl=位置[0]。GetProfitLoss(关闭[0][0],
绩效单位积分);
对于(int i=1;i
不,我想你明白了,我只是不知道简单的代码,+=是我需要的。谢谢实际上我似乎得到了不同的结果,是(int I=0;I<2;I++){unrlzdPnl+=Positions[I].GetProfitLoss(Closes[I][0],PerformanceUnit.Points);}等价于。。unrlzdPnl=((位置[0].GetProfitLoss(关闭[0][0],性能单位点数))+(位置[1].GetProfitLoss(关闭[1][0],性能单位点数));是的,应该是。如果你想确定,你可以打印出循环中的行,这将显示程序在每次迭代中循环的次数以及变量的值。在比较结果之前,不要忘记初始化unrlzdPnl
和最后乘以200
。另外,我隐式地假设unrlzdPnl是一个整数
,但如果不是这样,您应该使用适当的类型和初始化。好的,我得到了它,我初始化了unrlzdPnl,并认为它是coveredit,但我还需要将它放在方法中,以便在每次更新方法时重置它。节省了大量代码。谢谢语言是什么?JAVA我们编辑以添加该内容,请添加您的问题的更多详细信息。此问题是否已回答?你的意思不同吗?
int MyFunction(int nb_indices) {
if (1 > nb_indices)
return 0;
unrlzdPnl = Positions[0].GetProfitLoss(Closes[0][0],
PerformanceUnit.Points);
for (int i = 1; i < nb_indices; i++)
unrlzdPnl += Positions[i].GetProfitLoss(Closes[i][0],
PerformanceUnit.Points);
return unrlzPnl * 200;
}