2015-05-18 19 views
1

我正在学习java的基础知识,我完全不知道为什么我不能在主要方法中使用类。有人可以告诉我我的代码出错了吗?在java中使用多个类?

主类


package Base; 
    class Game { 
     public static void main(String[] args){ 
      Data gameData = new Data(); 
      gameData.test(); 
      System.out.println(score); 
    } 
} 

package Base; 

public class Data { 
    public void test(){ 
     int score = 100; 

    } 
} 
+3

所以,你甚至不打算提的问题是什么? – John3136

回答

2

您的代码存在的问题是您的main方法试图访问类Data的本地变量。与字段和函数不同,其他类的局部变量对嵌套的同一级别的类是禁止的*

为了解决这个问题,使scoreData一个成员变量,并添加一个getter方法做访问:现在

public class Data { 
    // Declaring score here makes it an instance variable 
    private int score; 
    // Giving score a getter lets others access the value, 
    // but it does not let them set the new score 
    public int getScore() { return score; } 
    // test() method can be used to set the score to a specific value 
    public void test(){ 
     score = 100; 
    } 
} 

main方法可以通过调用getScore()访问来自Datascore,像这样:

public static void main(String[] args){ 
    Data gameData = new Data(); 
    gameData.test(); 
    System.out.println(gameData.getScore()); 
} 

*嵌套类可以访问最终局部变量Ø在其中创建实例的f函数。

1

可变score是仅在Data类中的方法test()范围内,它不调用test()返回后继续存在。在主

public int test() { 
    int score = 100; 
    return score; 
} 

那么你将存储返回与调用test()

而不是仅仅在test()声明score你可以返回它

int score = gameData.test(); 

此时它会打印出你想要的分数。

1

例如,你可以在游戏中类参数得分添加到数据类这样

package Base; 

public class Data { 
    public int score = 0; 
    public void test(){ 
     score = 100; 
    } 
} 

然后:

package Base; 
    class Game { 
     public static void main(String[] args){ 
      Data gameData = new Data(); 
      gameData.test(); 
      System.out.println(gameData.score); 
    } 
}