[英]bad operand types for binary operator '*' how to covert the type to int
I'm having some problems with the following program. 我的以下程序有问题。
public static void main(String[] args) {
Int x =new Int(3);
int y= square() +twice() +once();
System.out.println(y);
}
private int square (Int x)
{
x= x*x;
return x;
}
private int twice (Int x)
{
x= 2*x;
return x;
}
private int once (Int x)
{
x= x;
return x;
}
and the output for this program should be 45. 该程序的输出应为45。
here is the Int class. 这是Int类。
public class Int {
private int x;
public Int (int x)
{
this.x=x;
}
the problem I have is in 我的问题是
private int square (Int x)
{
x= x*x;
return x;
}
x=x x gives an error of bad operand types for binary operator ' '.first type Int, Second Type Int. x = x x会为二进制运算符' ' 给出错误的操作数类型错误 。firsttype Int,Second Type Int。
I know for '*' to work it need an int type, I tried to use Integer.parseInt(x), but it says, x is not a string. 我知道要使'*'工作需要一个int类型,我尝试使用Integer.parseInt(x),但是它说x不是字符串。
can someone help me? 有人能帮我吗? what causes this problem and how to fix it.
是什么原因导致此问题以及如何解决。
The problem is simple: you define an Int
type and expect it to be implicitly convertible to a primitive int
but this has nothing to do with what your Int
type is expected to be in your design, it could be called Foo
instead that Int
but that would be the same. 问题很简单:您定义一个
Int
类型,并期望将其隐式转换为原始int
但这与您的Int
类型在设计中的预期无关,可以将其称为Foo
而不是Int
但是会是一样的。
If you want to be able to get the int
value wrapped inside an Int
instance then you must provide your own way to do it, eg: 如果要获取包装在
Int
实例中的int
值,则必须提供自己的方法,例如:
class Int {
int x;
public int intValue() { return x; }
}
so that you can do: 这样您就可以:
Int x = new Int(3);
int square = x.intValue() * x.intValue();
or, to avoid breaking encapsulation: 或者,为避免破坏封装:
class Int
{
int x;
public Int(int x) { this.x = x; }
public Int square() { return new Int(x*x); }
/* or: int square() { return x*x; }*/
}
Your class Int
looks (very lightly) like the Integer
wrapper. 您的类
Int
看起来(非常轻微)像Integer
包装器。 If you really need a wrapper, use the very tested Java Integer
, otherwise, use the primitive int
. 如果确实需要包装器,请使用经过
Integer
测试的Java Integer
,否则,请使用原始int
。 Remember, Java does not support operator overloading. 请记住,Java不支持运算符重载。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.