1
我正在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並超過10時,狗就不會死亡,數字還在繼續。 – artshof
在第一個答案中查看我的編輯。 Regards – mistic
@artshof你不應該讓你的狗死亡,永遠。讓它活下去,並讓它以不可理解的變量價值來對抗邏輯。否則,請選擇'sendDogBackInTime'。 :-) – afsantos