【问题标题】:"this." code blank output, main function“这。”代码空白输出,主函数
【发布时间】:2013-12-03 11:03:44
【问题描述】:

为什么这段代码不能产生它应该的输出?它应该返回:

1

42

MyThisTest a=42

代码输出为空白。每当我为“public static void main(String[] args)”设置大括号时,都会弹出很多红线错误。任何人都知道如何工作...

public class MyThisTest {
public static void main(String[] args){}
private int a;

public MyThisTest() {
this(42); // calls the other constructor
}

public MyThisTest(int a) {
this.a = a; // assigns the value of the parameter a to the field of the same name
}

public void frobnicate() {
int a = 1;

System.out.println(a); // refers to the local variable a
System.out.println(this.a); // refers to the field a
System.out.println(this); // refers to this entire object
}

public String toString() {
return "MyThisTest a=" + a; // refers to the field a
}
}

【问题讨论】:

  • 你应该添加语言标签。

标签: java function this


【解决方案1】:

你的主要功能是相当错误的。它应该创建一个MyThisTest 并在其上调用frobnicate()

类似

public static void main(String[] args)
{
   MyThisTest myThisTest;
   myThisTest.frobnicate();
}

【讨论】:

    【解决方案2】:

    你错过了 main 函数中的任何操作:

    public static void main(String[] args){}
    

    应该是:

    public static void main(String[] args)
    {
        MyThisTest thisTest = new MyThisTest();
    
        thisTest.frobnicate();
    }
    

    主函数是启动程序时调用的函数。 如果你在那里什么都不做,什么都不会发生。因此原始代码中的输出保持空白。

    【讨论】:

      【解决方案3】:

      main方法是java程序的起点,你需要在那里初始化对象。在初始化对象之前,无法调用您定义的构造函数。 frobncate 方法也是对象级别的方法,它只能在实例上调用。您应该在 main 方法中执行所有这些操作(正如其他人已经解释的那样)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-17
        • 2020-02-29
        • 2018-11-20
        • 2021-03-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多