Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/375.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 二进制运算符'*';如何将类型转换为int_Java - Fatal编程技术网

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
包装器。如果确实需要包装器,请使用经过测试的Java
Integer
,否则,请使用原语
int

请记住,Java不支持运算符重载。

parseInt()
需要向其传递字符串。您正试图传递一个
Int
对象。而且,您的
Int
类是非常无用的;您可以只使用原语
int
。谢谢,但我不想在int类中使用公共int intValue()。我想在main方法下保留private方法。有没有办法保持我的Int类不变,并使x=x*x在私有方法中工作?