【问题标题】:I need to use a variable from the main class into another class created by me [closed]我需要将主类中的变量用于我创建的另一个类[关闭]
【发布时间】:2021-03-24 05:35:23
【问题描述】:

我正在用 java 创建一个基于文本的游戏。在这个游戏中我创建了一个名为“name”的变量,这个变量有一个来自用户的字符串输入。

System.out.println("You chose to play, welcome to the game!");
      System.out.println("You can choose your name now!");
      System.out.print("My name is --> ");
      input.nextLine(); 
      String name = input.nextLine();
      System.out.println("Are you sure your name is " + name + "?");
      System.out.println("1. Yes, that is my name. Time to move on...");
      System.out.println("2. No, that isn't my name...");
      int u = 2;
      u = input.nextInt();
        while (u == 2){
          System.out.println("Then let's change your name!");
          System.out.println("What is your new name?");
          input.nextLine(); 
          name = input.nextLine();
          System.out.println("Are you sure your name is " + name + "?");
          System.out.println("1. Yes, that is my name. Time to move on...");
          System.out.println("2. No, that isn't my name...");
          u = input.nextInt();
        }

所以我希望在 Character 类中使用变量“name”,如下所示。

class Character{
  public static void full_stats(){
    System.out.println("This is your name" + name);
  }
}

【问题讨论】:

  • 正确的设计是让name 成为Character 的字段。然后在 Main 类中创建 Character 的实例,并通过其对应的 setter 为 name 字段赋值,将用户的输入作为参数传递给 setter。
  • 在 Character 类中有一个名称字段。然后将名称传递给 Character 构造函数。您可能希望将您的类重命名为 GameChar 或其他名称,因为如果您想使用 java 中的普通 Character 类,这可能会导致奇怪的错误。

标签: java class variables


【解决方案1】:

以你现在的方式,你不能。

我能想到两种方法:

将名称声明为类级变量:

static String name;
public static void main(String[]args ) {
 //.. other code
 name = setYourName();
 //..
 Character.full_stats();
}


class Character{
  public static void full_stats(){
    System.out.println("This is your name" + Main.name);
  }
}

更好的方法,将名称作为参数传递:

class Character{
  public static void full_stats(String name){
    System.out.println("This is your name" + name);
  }
}

public static void main(String[]args ) {
 //.. other code
 String name = setYourName();
 //..
 Character.full_stats(name);
}

不过,我建议您在主方法/类中保留尽可能少的代码。它只是一个入口点,而不是你的整个应用程序。

另外:遵循标准命名约定将使您的代码更容易被非编写者维护/遵循。

【讨论】:

  • 非常感谢,这回答了我的问题。抱歉这么晚才回复,我把问题放在了溢出上,离开了电脑,因为我不得不去某个地方。
  • @The_Red_Baron 如果这回答了您的问题,您能否将答案标记为“已接受”?
【解决方案2】:

为方法添加参数

class Character{
  public static void full_stats(String name){
    System.out.println("This is your name" + name);
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-10
    • 2012-05-02
    • 2019-02-07
    • 2017-04-03
    • 1970-01-01
    相关资源
    最近更新 更多