簡體   English   中英

Java,將字符串從一個類傳遞到另一個類

[英]Java, passing strings from one class to another

在下面的代碼我做錯了。 對不起,如果這有點基礎。 如果它只是在一個類中,那么我的工作正常,但是當我在下面的代碼中打破類時,我的工作正常:

class Apples{
    public static void main(String[] args){

        String bucket = "green"; //instance variable

        Apples appleOne = new Apples(); //create new object (appleOne) from Apples class

        System.out.println("Paint apple one: " + appleOne.paint(bucket));
        System.out.print("bucket still filled with:" + bucket);

        }//end main

    }//end class

class ApplesTestDrive{

    public String paint(String bucket){

        bucket = "blue"; //local variable
        return bucket;

        }//end method

    }//end class

錯誤信息:

location:class Apples
cannot find symbol
pointing to >> appleOne.paint(bucket)

任何提示?

您需要創建ApplesTestDrive的實例,而不是Apples 方法就在那里。

所以,而不是

Apples appleOne = new Apples();

ApplesTestDrive appleOne = new ApplesTestDrive();

這與通過引用傳遞無關(所以我從你的問題中刪除了標記)。 這只是程序員錯誤(實際上所有編譯錯誤都是)。

您正在Apple對象上調用方法paint但是paint方法在AppleTestDrive類中。

請改用此代碼:

AppleTestDrive apple = new AppleTestDrive();
apple.paint(bucket);

System.out.println("Paint apple one: " + appleOne.paint(bucket)); paint是ApplesTestDrive類的一種方法,而appleOne是一個Apples objject,所以你不能在這里調用appleOne.paint。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM