我正在用Java制作游戏,你必须照顾好狗。我让我的游戏方法调用自己,这样我就不必多次复制和粘贴这个方法中的内容了。问题是我不知道如何绕过我声明的两个整数值,因为通过每个选项添加和减去整数值并再次调用该方法会将这些更改的值更改回默认值。
import java.io.File;
import java.util.Scanner;
public class Main {
public static Scanner kybd = new Scanner(System.in);
public static void main(String[] args) {
game();
}
public static void game() {
Integer diet;
diet = 5;
Integer happiness;
happiness = 10;
System.out.println("");
System.out.println("Dog \t Hunger: " + diet
+ "\n \t Happiness: " + happiness);
System.out.println("");
System.out.println("1. Feed \n2. Play \n3. Ignore");
System.out.println("");
System.out.print("> ");
String input = kybd.nextLine();
if (input.equalsIgnoreCase("1")) {
diet++;
game(); // This is supposed to go to the
// beginning with the changed value of diet.
} else if (input.equalsIgnoreCase("2")) {
happiness++;
game(); // This is supposed to go to the
// beginning with the changed value of happiness.
} else if (input.equalsIgnoreCase("3")) {
happiness--;
diet--;
game(); // This is supposed to go to the
// beginning with the changed value of happiness.
} else {
System.out.println("Invalid Input");
game(); // This is supposed to go the beginning
// where you can change your input but
// still has your changed values.
}
if (diet <= 0);
{
System.out.println("Your dog died because it did not eat.");
game(); // This is supposed to go to the beginning
// with the default values.
}
if (diet > 10);
{
System.out.println("Your dog died because it was overfed.");
game(); // This is supposed to go to the
// beginning with the default values.
}
if (happiness <= 0);
{
diet--;
System.out.println("Your dog is no longer happy. He will not eat.");
}
{
if (happiness > 10);
System.out.println("Your dog died because it was too excited.");
game(); // This is supposed to go to the
// beginning with the default values.
}
}
}
答案 0 :(得分:1)
如果我以正确的方式理解你的问题,你唯一要做的就是将这两个变量声明为类变量(静态或非静态)。所以最终的代码是:
import java.io.File;
import java.util.Scanner;
public class Main {
public static Scanner kybd = new Scanner(System.in);
public static int diet = 5;
public static int happiness = 10;
public static void main(String[] args) {
game();
}
此致
为狗狗编辑
public static die() {
diet=5;
happiness=10;
}
每次你的狗在电话游戏()之前死亡时调用此函数。