java 基本的 android:switch 语句而不是 else-if 的语法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6405710/
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-10-30 15:46:49  来源:igfitidea点击:

basic android: syntax for switch statement instead of else-if

javaandroidsyntaxif-statement

提问by untriangulated

I am working on an android beginner's tutorial that is a tip calculator. It runs properly, but I was wondering how to replace the else-if statement with a switch statement. Not that it is that important for the purposes of this program, but I'm just trying to wrap my mind around the syntax.

我正在编写一个 android 初学者教程,它是一个小费计算器。它运行正常,但我想知道如何用 switch 语句替换 else-if 语句。并不是说它对这个程序的目的来说那么重要,但我只是想把我的想法放在语法上。

package com.android.tipcalc;

import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Button;
import android.widget.RadioButton;
import android.view.View;

public class tipcalc extends Activity
{

    private EditText txtbillamount;
    private EditText txtpeople;
    private RadioGroup radiopercentage;
    private RadioButton radio15;
    private RadioButton radio18;
    private RadioButton radio20;

    private TextView txtperperson;
    private TextView txttipamount;
    private TextView txttotal;

    private Button btncalculate;
    private Button btnreset;

    private double billamount = 0;
    private double percentage = 0;
    private double numofpeople = 0; 
    private double tipamount = 0;
    private double totaltopay = 0;
    private double perperson = 0; 


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        initControls();

    }

    private void initControls()
    {
        txtbillamount = (EditText)findViewById(R.id.txtbillamount);
        txtpeople = (EditText)findViewById(R.id.txtpeople);
        radiopercentage = (RadioGroup)findViewById(R.id.radiopercentage);
        radio15 = (RadioButton)findViewById(R.id.radio15);
        radio18 = (RadioButton)findViewById(R.id.radio18);
        radio20 = (RadioButton)findViewById(R.id.radio20);
        txttipamount=(TextView)findViewById(R.id.txttipamount);
        txttotal=(TextView)findViewById(R.id.txttotal);
        txtperperson=(TextView)findViewById(R.id.txtperperson);

        btncalculate = (Button)findViewById(R.id.btncalculate);
        btnreset = (Button)findViewById(R.id.btnreset);

        btncalculate.setOnClickListener(new Button.OnClickListener() {
            public void onClick (View v){ calculate(); }});
        btnreset.setOnClickListener(new Button.OnClickListener() {
            public void onClick (View v){ reset(); }});

    }

    private void calculate()
    {
    billamount=Double.parseDouble(txtbillamount.getText().toString());
    numofpeople=Double.parseDouble(txtpeople.getText().toString());

    if (radio15.isChecked()) {
        percentage = 15.00;
    } else if (radio18.isChecked()) {
        percentage = 18.00;
    } else if (radio20.isChecked()) {
        percentage = 20.00;
    }

    tipamount=(billamount*percentage)/100;
    totaltopay=billamount+tipamount;
    perperson=totaltopay/numofpeople;

    txttipamount.setText(Double.toString(tipamount));
    txttotal.setText(Double.toString(totaltopay));
    txtperperson.setText(Double.toString(perperson));        
    }

    private void reset()
    {
    txtbillamount.setText("");
    txtpeople.setText("");
    radiopercentage.clearCheck();
    radiopercentage.check(R.id.radio15);
    txttipamount.setText("...");
    txttotal.setText("...");
    txtperperson.setText("...");
    }
}

回答by Jason Robinson

What the people above me said is correct, but for the sake of using a switch statement for the hell of it, you could set an OnCheckedChangedListeneron your RadioGroup, then use a class like this:

我上面的人说的是正确的,但为了使用 switch 语句,你可以OnCheckedChangedListener在你的上设置 an RadioGroup,然后使用这样的类:

private class MyCheckedChangedListener implements OnCheckedChangeListener {

@Override
public void onCheckedChanged( RadioGroup group, int checkedId ) {

    switch (checkedId) {
        case R.id.radio15:
            percentage = 15f;
            break;
        case R.id.radio18:
            percentage = 18f;
            break;
        case R.id.radio20:
            percentage = 20f;
            break;
    }
}

}

}

回答by Vladislav Zorov

A switchis used on one variable - i.e. you have x, which can equal 3,5 or 7. Then you switch xand give several cases - what to do on each possible value (you can also have a default case, when none of the given values match). In your case, you're checking several different variables, so if ... else if ... elseis the correct method. You can, of course, make the radio boxes set a shared variable, which you can then switch.

Aswitch用于一个变量 - 即你有x,它可以等于 3,5 或 7。然后你switch x并给出几种情况 - 对每个可能的值做什么(你也可以有一个默认情况,当给定的值都不匹配时)。在您的情况下,您正在检查几个不同的变量,因此if ... else if ... else是正确的方法。当然,您可以让单选框设置一个共享变量,然后就可以了switch

回答by Ted Hopp

If you're talking about the if-else statements in calculate(), you can't replace it directly with a switch statement. The case values in a switch statement need to be compile-time constants (either integers or enum values). Besides, the if-else here perfectly expresses the logic of what you are trying to do.

如果您在谈论 中的 if-else 语句calculate(),则不能直接用 switch 语句替换它。switch 语句中的 case 值需要是编译时常量(整数或枚举值)。此外,这里的 if-else 完美地表达了您正在尝试做的事情的逻辑。

You couldcompute a "switch test value" based on the states of radio15, radio18, and radio20 (say, an integer from 0 to 8, based on the eight possible combinations of values) and switch on that, but I would strongly recommend against such an approach. Not only would it needlessly complicate and obscure the logic of what's going on, you would be cursing yourself if you needed to maintain the code six months from now after you had forgotten the clever trick.

可以根据 radio15、radio18 和 radio20 的状态(例如,从 0 到 8 的整数,基于八种可能的值组合)计算“开关测试值”并打开它,但我强烈建议不要这样的做法。它不仅会不必要地使正在发生的事情的逻辑复杂化和模糊,而且如果您在忘记这个聪明的技巧六个月后还需要维护代码,您会诅咒自己。