问题描述
我收到错误
我的第一次尝试在一个Android应用程序无法在float基本类型调用字符串()
I am getting the error "Cannot invoke String() on the primitive type float"
on my first attempt at an android app:
这是code:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void calculate(View v){
EditText number1text = (EditText)findViewById(R.id.a);
EditText number2text = (EditText)findViewById(R.id.b);
EditText number3text = (EditText)findViewById(R.id.c);
Integer num1 = Integer.parseInt(number1text.getText().toString()) ,
num2 = Integer.parseInt(number2text.getText().toString()),
num3 = Integer.parseInt(number3text.getText().toString());
if ((num2 ^ 2) - (4*num1*num3) < 0){
break;
}
float ans = (float) ((-(num2)- Math.sqrt(num2^2 - (4*num1*num3)))/2*num1);
float ans2 = (float) ((-(num2)+ Math.sqrt(num2^2 - (4*num1*num3)))/2*num1);
TextView answer = (TextView)findViewById(R.id.ans1);
answer.setText("The Answer is: " + ans.toString());
TextView answer2 = (TextView)findViewById(R.id.ans2);
answer.setText("The Answer is: " + ans2.toString());
}
private TextView getText(String string) {
return null;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
当我尝试调用时出现错误 ans.toString()
和 ans2.toString()
。
The error occurs when I try to call ans.toString()
and ans2.toString()
.
推荐答案
您不能调用的toString
(或方法)上的任何原始类型,如浮动
。然而,字符串
转换将其转换为字符串
为您提供 +
运营商无妨。
You cannot call toString
(or any method) on any primitive type, such as float
. However, String
conversion will convert it to a String
for you with the +
operator anyway.
answer.setText("The Answer is: " + ans);
如果您需要更多的控制权的显示格式,可以使用 DecimalFormat的
。
If you need more control over the display format, you can use a DecimalFormat
.
此外,这个前pression没有做什么,你认为它。
Additionally, this expression doesn't do what you think it does.
(num2 ^ 2)
的 ^
运算符是一个按位异或在Java中,没有幂。用途:
The ^
operator is a bitwise-XOR in Java, not exponentiation. Use:
num2 * num2
这篇关于错误:&QUOT;不能对float基本类型&QUOT调用字符串();在二次公式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!