我正在使用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("");
}
}
< p>你看,在我的方法Hi()中,x应该是一个错误。错误读取“找不到符号 - 变量x”,即使我扩展了类并在另一个类中声明了一个对象...任何帮助?
答案 0 :(得分:0)
您可以像这样声明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();
}
}