[英]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.