[英]Using a variable from the driver class in another class' method (java)
我正在用面向对象的方法用Java编写我的第一个程序。 到目前为止,我一直在学习使用顺序方法进行Java编程,但是转向面向对象给我带来了一些问题。
首先,我的程序是一个简单的程序,可以使虚拟狗执行一些技巧。 我有一个狗类和一个dogDriver类。 在我的dogDriver类中,我有以下代码片段:
System.out.println("\nWhat trick shall Sparky do?");
System.out.println("Roll Over");
System.out.println("Jump");
System.out.println("Sit");
System.out.println("Bark");
System.out.print("\nYour command: ");
String command = keyboard.nextLine();
但是,在我的狗类中,我希望在一个方法中检索输入的命令并在其中执行计算,例如:
public String getResponse()
{
if (command.equalsIgnoreCase("Roll Over"))
{
// Roll Over Code
response = "I just Rolled Over!";
}
// rest of the commands
return response;
}
我相信一个简单的选择是在驱动程序类中公开变量'command'并使用:
if (dog.command.equalsIgnoreCase("Roll Over"))
// rest of code
但我不建议将变量公开。 从我收集到的信息中,我可以使用“返回'变量”将变量的值返回到驱动程序类,但是如何从驱动程序类将变量的值返回到类(即狗)?
为什么不按如下所示在Dog类中更改getResponse方法的签名:
public String getResponse(final String command)
{
if (command.equalsIgnoreCase("Roll Over"))
{
// Roll Over Code
response = "I just Rolled Over!";
}
// rest of the commands
return response;
}
据我了解,您将在DogDriver类中创建Dog类的实例。 您可以调用getResponse并将用户输入命令传递给它。
M混淆了您所问的,我所理解的是您无法将响应返回给狗驱动程序类,因此只能从您的狗驱动程序类中调用getResponse方法:
public class DogDriver{
public static void main(String args[]){
System.out.println("\nWhat trick shall Sparky do?");
System.out.println("Roll Over");
System.out.println("Jump");
System.out.println("Sit");
System.out.println("Bark");
System.out.print("\nYour command: ");
final String command = keyboard.nextLine();
Dog dog = new Dog();
String response = dog.getResponse(command);
System.out.println(response);
}
}
您的狗类代码将是
public String getResponse(final String command)
{
if (command.equalsIgnoreCase("Roll Over"))
{
// Roll Over Code
response = "I just Rolled Over!";
}
// rest of the commands
return response;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.