简体   繁体   English

简单的Java程序错误

[英]Simple Java program error

I'm a Java beginner, and here's my issue : I don't understand why my output is "null" while implemanting my Print program. 我是Java初学者,这是我的问题:在实现我的Print程序时,我不明白为什么我的输出为“ null”。 As I understand my code, it is supposed to display :" http://www.google.com ". 据我了解,我的代码应该显示为:“ http://www.google.com ”。 I tried with a StringBuilder, and I still have this problem. 我尝试使用StringBuilder,但仍然遇到此问题。 Could someone give me some help please ? 有人可以给我些帮助吗? Thanks 谢谢

URL.java : URL.java:

public class URL { 公共类网址{

    String url;

    public void create(){
        url = new String();
        url+=("http://www.google.com");
    }

    public String geturl() {
         return this.url;
    } 

} }

Print.java : Print.java:

public class Print { 公共课打印{

public static  void main(String[] args) throws Exception {
URL link = new URL();   
System.out.print(link.geturl());
}

} }

You need to call link.create() , or change the create() function to be a constructor instead. 您需要调用link.create() ,或将create()函数更改为构造函数。 Like this: 像这样:

public URL(){
    url = new String();
    url+=("http://www.google.com");
}

An even better approach is to initialize the url instance variable within a constructor. 更好的方法是在构造函数中初始化url实例变量。 By doing that the url instance variable will automatically be initialize when you create an instance of URL class and you eliminate the need for the create method. 这样,当您创建URL类的实例时,将自动初始化url实例变量,从而无需使用create方法。

 public class URL{
     private String url;

     //Constructor
     public URL (){
        url = "http://www.google.com";
     }

     public String getUrl (){
        return url;
     }

 }

 public class Print{
      public static void main (String[] args){
         URL url = new URL ();
         System.out.println (url.getUrl());

      }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM