如何使用yes或no添加重置游戏?游戏Java

时间:2019-01-27 11:56:11

标签: java

我不知道如何使用yes或no输入用户添加重置游戏 我已经尝试了许多解决方案,但没有用。

这是我的代码:

import java.util.Scanner;

public class Pr16 {

public static void main(String[] args) {

    Scanner in = new Scanner(System.in);
    String a = "Stone";
    String b = "Scissors";
    String c = "Paper";
    //a > b
    //b > c
    //c > a

    System.out.println("Player one choose:");

    String x = in.nextLine();

    System.out.println("Player two choose:");

    String y = in.nextLine();

    String answer = "";

    do {
            if ((x.equalsIgnoreCase(a) && (y.equalsIgnoreCase(b)))) {
                System.out.println("Player one won");
            } else if ((x.equalsIgnoreCase(b) && (y.equalsIgnoreCase(c)))) {
                System.out.println("Player one won");
            } else if ((x.equalsIgnoreCase(c) && (y.equalsIgnoreCase(a)))) {
                System.out.println("Player one won");
            } else {
                System.out.println("Player two won");
            }
        System.out.println("Do you want to play again? YES / NO");
        answer= in.nextLine();
        }

        while (answer.equalsIgnoreCase("YES"));
        if (answer.equalsIgnoreCase("NO")){
            System.out.println("Goodbye!");
        }
    }
}

有什么方法可以将游戏重置添加到我的上述代码中?任何建议将不胜感激。

1 个答案:

答案 0 :(得分:0)

尝试以下代码:

public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        String a = "Stone";
        String b = "Scissors";
        String c = "Paper";
        //a > b
        //b > c
        //c > a
            String answer = "";
        do {
            System.out.println("Player one choose:");

            String x = in.nextLine();

            System.out.println("Player two choose:");

            String y = in.nextLine();

            answer = "";

            if ((x.equalsIgnoreCase(a) && (y.equalsIgnoreCase(b)))) {
                System.out.println("Player one won");
            } else if ((x.equalsIgnoreCase(b) && (y.equalsIgnoreCase(c)))) {
                System.out.println("Player one won");
            } else if ((x.equalsIgnoreCase(c) && (y.equalsIgnoreCase(a)))) {
                System.out.println("Player one won");
            } else {
                System.out.println("Player two won");
            }
            System.out.println("Do you want to play again? YES / NO");
            answer= in.nextLine();
        }

        while (answer.equalsIgnoreCase("YES"));
        if (answer.equalsIgnoreCase("NO")){
            System.out.println("Goodbye!");
        }
    }

如果您愿意,可以制作2个类,这样会更干净,但是此答案将在您的主要功能中完成工作,而无需其他类