【问题标题】:Operater '*' cannot be applied to 'android.widget.RadioButton', 'int'运算符 '*' 不能应用于 'android.widget.RadioButton', 'int'
【发布时间】:2018-04-30 17:49:36
【问题描述】:

运算符 '*' 不能应用于 'android.widget.RadioButton', 'int'

我正在创建一个应用程序,该应用程序使用单选按钮打印纸张的成本,纸张限​​制为 20 个。 我不确定为什么会收到此错误,因为我正在从我的 EditText 获取信息。

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

import java.text.DecimalFormat;

public class MainActivity extends Activity {
double totalcost;
double price1 = 0.15;
double price2 = 0.45;
double price3 = 0.80;
int prints;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    getActionBar().setDisplayHomeAsUpEnabled(true);
    getActionBar().setLogo(R.mipmap.ic_launcher);
    getActionBar().setDisplayUseLogoEnabled(true);
    final EditText prints =(EditText)findViewById(R.id.noprint);
    final RadioButton price1 = (RadioButton)findViewById(R.id.rad1);
    final RadioButton price2 = (RadioButton)findViewById(R.id.rad2);
    final RadioButton price3 = (RadioButton)findViewById(R.id.rad3);
    final TextView totalcost =(TextView)findViewById(R.id.cost);
    Button calculate =(Button)findViewById(R.id.btn1);
    calculate.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            String prints = noprint.getText().toString();
            int prints = Integer.parseInt(noprint);
            DecimalFormat tenth = new DecimalFormat("$##.##");

            if (price1.isChecked()) {
                if (prints <= 20) {
                    totalcost = price1 * prints;

                } else {
                    Toast.makeText(MainActivity.this, "Number of prints must be less than 20", Toast.LENGTH_LONG).show();
                }

            }

【问题讨论】:

  • price1 在方法onCreate(...) 中定义为final RadioButton price1 = (RadioButton)findViewById(R.id.rad1);,Java 不知道如何将int 与RadioButton 相乘。因此错误。
  • 为您的RadioButtons 使用不同的变量名称

标签: android operator-keyword


【解决方案1】:

查看您的程序,您遇到了命名问题。在类级别上,您定义一个属性

double price1 = 0.15;

但在方法onCreate(...) 中你也定义了

final RadioButton price1 = (RadioButton)findViewById(R.id.rad1);

它有效地隐藏了属性。因此,当你写

totalcost = price1 * prints;

您命令 java 将 RadioButton 与 int 相乘。由于此二元运算符 (*(RadioButton, int)) 在 Java 中未定义,因此您会收到编译器错误。您的意图可能是使用属性price1。一个快速的解决方法是通过this 参考明确使用该属性:

totalcost = this.price1 * prints;

更简洁的解决方法是重命名变量,这样您就不会使用局部变量隐藏属性。

【讨论】:

  • 谢谢,有帮助
猜你喜欢
  • 1970-01-01
  • 2019-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-29
  • 2017-09-02
  • 1970-01-01
相关资源
最近更新 更多