如何在按钮之间使用相同的变量?

发布于 2025-01-28 10:34:43 字数 1008 浏览 3 评论 0原文

我在Java中创建了一个岩石剪刀游戏,但是我不知道如何使用相同的变量在3个不同的按钮(岩石,纸剪刀)之间工作。我使用如果循环进行胜利损失并在每个按钮中绑扎,这样我就可以轻松地将1添加到一个变量中,但是我不确定如何使其在代码中到处都可以工作,甚至可以做到这一点。

if (playerChoice.equals(randomChoice)) //If player chose the same thing as the computer
{
    //TIE
    System.out.println("user tied"); //Tie the game with output message in console
    lblGameStatus.setText("The game tied!"); //Output to the user for the result of the game
}
if (randomChoice.equals("paper")) //and if the computer chose paper
{
    //ROCK VS PAPER
    System.out.println("user won");//The player wins, with output message in console
    lblGameStatus.setText("You Won!"); //Output to the user for the result of the game
    
}
else if (randomChoice.equals("scissors")) //if the computer chose scissors instead of paper
{
    //ROCK VS SCISSORS
    System.out.println("user lost"); //the computer wins, display output message in console
    lblGameStatus.setText("You Lost!"); //Output to the user for the result of the game
}

I've created a rock paper scissors game in java, but I don't know how I could use the same variable to work between 3 different buttons (rock, paper scissors). I use if loops for win loss and tie in each button so I could easily just add 1 to a variable but I'm not sure how to make it work everywhere in my code and if that is something even possible.

if (playerChoice.equals(randomChoice)) //If player chose the same thing as the computer
{
    //TIE
    System.out.println("user tied"); //Tie the game with output message in console
    lblGameStatus.setText("The game tied!"); //Output to the user for the result of the game
}
if (randomChoice.equals("paper")) //and if the computer chose paper
{
    //ROCK VS PAPER
    System.out.println("user won");//The player wins, with output message in console
    lblGameStatus.setText("You Won!"); //Output to the user for the result of the game
    
}
else if (randomChoice.equals("scissors")) //if the computer chose scissors instead of paper
{
    //ROCK VS SCISSORS
    System.out.println("user lost"); //the computer wins, display output message in console
    lblGameStatus.setText("You Lost!"); //Output to the user for the result of the game
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文