【问题标题】:How can I use a Variable from a Class Runner to use in a Method in another Class? (BlueJ, Java)如何使用类运行器中的变量在另一个类的方法中使用? (BlueJ,Java)
【发布时间】:2017-12-22 23:55:11
【问题描述】:

我正在上一个使用 BlueJ 的编码课程,并决定用一个使用 Class Runner 和另一个类来调用方法的 Text Adventure 给我的老师一个惊喜。问题是,我不知道如何将我在 Runner 中建立的变量使用到 Method Class 中的方法中,然后我将其调用到 Runner 中。这是我的代码:

(这是跑步者)

import java.util.*;
public class TextAdventureRunner
{
    public static void main (String[]Args)
    {
    TextAdventureCode run = new TextAdventureCode();
    Scanner kb = new Scanner(System.in);

    String x = "";
    System.out.print("Enter Your Name: : ");
    x = kb.nextLine();
    System.out.println(x);

    run.Hi();
    run.HiTwo();
    }
}

(这是包含方法的代码)

import java.util.*;
public class TextAdventureCode extends TextAdventureRunner
{
Scanner kb = new Scanner(System.in);

    public static void Hi()
    {
        System.out.println("Hi" + x);
    }

    public static void HiTwo()
    {
        System.out.println("");
    }

}

你看,在我的方法 Hi() 中,x 应该在的地方有一个错误。即使我扩展了类并在另一个类中声明了一个对象,错误仍显示为“找不到符号 - 变量 x”......有什么帮助吗?

【问题讨论】:

    标签: java bluej


    【解决方案1】:

    您可以像这样声明您的 TextAdventureCode:

     import java.util.*;
    public class TextAdventureCode extends TextAdventureRunner
    {
    Scanner kb = new Scanner(System.in);
    
        public static void Hi(String x) //Modification
        {
            System.out.println("Hi" + x);
        }
    
        public static void HiTwo()
        {
            System.out.println("");
        }
    }
    

    并像这样声明 TextAdventureRunner:

        import java.util.*;
        public class TextAdventureRunner
        {
        public static void main (String[]Args)
        {
        TextAdventureCode run = new TextAdventureCode();
        Scanner kb = new Scanner(System.in);
    
        String x = "";
        System.out.print("Enter Your Name: : ");
        x = kb.nextLine();
        System.out.println(x);
    
        run.Hi(x);  // Modification
        run.HiTwo();
        }
    }
    

    【讨论】:

    • 很高兴听到这个消息。 :)
    猜你喜欢
    • 1970-01-01
    • 2020-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-08
    • 1970-01-01
    相关资源
    最近更新 更多