【问题标题】:Reduce the number of lines in code in android java program减少android java程序中的代码行数
【发布时间】:2015-09-18 06:36:09
【问题描述】:

我自己sujay。我对android编程很陌生。我编写了一个程序来转换我们在纺织领域使用的值。有些值是直接成比例的,有些是间接成比例的。我在下面写的代码可以帮助我用其他一些 JAVA 代码减少程序中的行数

  public void onClick(View v)
{

    int index1 = spinner11.getSelectedItemPosition();
    int index2 = spinner21.getSelectedItemPosition();
    double value = 0;
    if (from.getText().toString().isEmpty())
        Toast.makeText(getApplicationContext(), getResources().getString(R.string.toastmessage1),
                Toast.LENGTH_LONG).show();
    else {
        value = Double.parseDouble(from.getText().toString());
    }
    //From Ne
    if (index1 == 0 && index2 == 0 )//Ne to Ne
    {
        double result = value*1;
        to.setText(result+"");
    }
    if (index1 == 0 && index2 == 1) //Ne to Nm
    {
        double result = value * 1.69;
        to.setText(result+"");
    }
    if (index1 == 0 && index2 == 2)//Ne to Tex
    {
        double result = 591/value;
        to.setText(result+"");
    }
    if(index1 == 0 && index2 == 3)//Ne to kTex
    {
        double result = 0.591/value;
        to.setText(result+"");
    }
    if (index1 == 0 && index2 == 4)//Ne to Denier
    {
        double result = 5314/value;
        to.setText(result+"");
    }
    if (index1 == 0 && index2 == 5)//Ne to Denier
    {
        double result = 5314/value;
        to.setText(result+"");
    }
    if (index1 == 0 && index2 == 6)//Ne to Denier
    {
        double result = 5314/value;
        to.setText(result+"");
    }
    if (index1 == 0 && index2 == 7)//Ne to Denier
    {
        double result = 5314/value;
        to.setText(result+"");
    }

【问题讨论】:

  • 您可以在每个 if 块 to.SetText(""+(value*1)); 中减少一行,而无需将其分配给本地/块变量..

标签: java android


【解决方案1】:

这会稍微减少行数:

double result = 0.0;
if (index1 == 0)//Ne to Ne
{
    if(index2 == 0)
        result = value*1;

    if (index2 == 1) 
        result = value * 1.69;

    if (index2 == 2)
        result = 591/value;

    if(index2 == 3)
       result = 0.591/value;

    if (index2 == 4 || index2 == 5 || index2 == 6 || index2 == 7)
        result = 5314/value;

}
to.setText(result+"");

希望对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-07
    • 1970-01-01
    • 1970-01-01
    • 2018-02-28
    • 1970-01-01
    • 2021-12-30
    • 2017-12-30
    • 2018-07-13
    相关资源
    最近更新 更多