Java 二进制运算符'*';如何将类型转换为int
我对下面的程序有一些问题Java 二进制运算符'*';如何将类型转换为int,java,Java,我对下面的程序有一些问题 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;
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;
}
这个程序的输出应该是45
这是Int类
public class Int {
private int x;
public Int (int x)
{
this.x=x;
}
我的问题在于
private int square (Int x)
{
x= x*x;
return x;
}
x=xx给出了二进制运算符“”的错误操作数类型。第一种类型为Int,第二种类型为Int
我知道“*”需要一个int类型,我尝试使用Integer.parseInt(x),但它说,x不是字符串
有人能帮我吗?
造成此问题的原因和解决方法。问题很简单:定义
Int
类型并期望它隐式转换为基元Int
,但这与设计中的Int
类型无关,它可以被称为Foo
,而不是Int
,但这是相同的
如果希望能够将int
值包装在int
实例中,则必须提供自己的方法,例如:
class Int {
int x;
public int intValue() { return x; }
}
因此,您可以:
Int x = new Int(3);
int square = x.intValue() * x.intValue();
或者,为了避免破坏封装:
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; }*/
}
您的类
Int
看起来(非常轻)像Integer
包装器。如果确实需要包装器,请使用经过测试的JavaInteger
,否则,请使用原语int
。
请记住,Java不支持运算符重载。
parseInt()
需要向其传递字符串。您正试图传递一个Int
对象。而且,您的Int
类是非常无用的;您可以只使用原语int
。谢谢,但我不想在int类中使用公共int intValue()。我想在main方法下保留private方法。有没有办法保持我的Int类不变,并使x=x*x在私有方法中工作?