有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java是跨类实现和维护价值的最佳方式

所以,为了好玩,在我上大学的早期,我决定安排各种项目是一种很好的做法。我正在做的一个项目基本上就是一个基于文本的游戏。我正在实施咒语和能力,我有一个字符串数组给我的敌人,我想把这个代码生成的随机值(敌人)保存到我的能力类中进行计算。我是否应该参加另一门技能和咒语课程?我不完全确定我是否在正确的轨道上发展正确的面向对象编程实践和习惯,所以如果有人能帮我指出正确的道路,我将不胜感激

System.out.println("Welcome to Mysterical World of Mysterical Things!");
System.out.println("Please press the number corresponding the action you wish to take.");   
//Clause to keep the game running with invalid inputs
GAME:


while(running) {
    System.out.println("-----------------------------------------------");
    int enemyHealth = rand.nextInt(maxEnemyHealth);
    String enemy = enemies[rand.nextInt(enemies.length)];
    System.out.println("\t### " + enemy + " has appeared! ###\n");

我试图维护字符串敌人值的类是:

public void fireBlast(int fb) {

    fb = 5;

    System.out.println("You cast Fire Blast!");
    int damageTaken = rand.nextInt(enemyAttackDmg);
    enemyHealth -= fb*level;
    health -= damageTaken;
    System.out.println("\t>>> You hit the " + enemy + " for " + fb + " damage <<<");
    System.out.println("\t>>> You took " + damageTaken + " <<<");

共 (1) 个答案

  1. # 1 楼答案

    根据经验,globals=badEvil Globals

    当然,如果你坚持使用方法而不是类,你可以在main()之外声明类变量

    不过你也有一些选择。您可以将字符串或字符串[]作为参数传入希望访问它们的函数中。所以如果你有一些敌人的字符串[],你想把它们传递到另一个类的函数中

    MiddleEarth me = new MiddleEarth(); // MiddleEarth is a class, me is the instance of that class
    me.mordor(enemies); // I have now passed the enemies into the function Mordor of the class MiddleEarth
    

    现在,在中间的地级类中,你需要MiDORE()接受一个字符串或字符串[]敌人:

    public class MiddleEarth {
      public MiddleEarth() {
        //constructor
      }
    
      public void mordor(String[] enemies) {
        // do something with enemies
      }
    }
    

    另一个不太可取的选择是使用一个名为Globals的接口,存储希望从其中的所有类访问的变量,并在希望访问这些全局变量的类中实现该接口<我一点也不推荐这个

    还有——如果第一次精简设置为5,为什么要将int fb传递给fireBlast()?这违背了目的