【问题标题】:How to call a method variable in another method?如何在另一个方法中调用方法变量?
【发布时间】:2022-01-06 13:33:59
【问题描述】:

我需要了解如何将computerChoice 方法的返回值转换为playGame 方法以打印出计算机的随机选择。

最后一个方法在 print 语句之后没有完成;我只是卡在这部分。

import java.util.Random;

public class RockPaperScissors
{
    private InputReader reader;
    private int yourScore;
    private int computerScore;
    private Random ran;

   
    public RockPaperScissors()
    {
        reader = new InputReader();
        yourScore = 0;
        computerScore = 0;
        ran = new Random(1);
    }


    public void printPrompt()
    {
        System.out.println();
        System.out.println();
        System.out.println("Enter your choice, paper, rock or scissors >");
       
    }
    
    public String userChoice()
    {
        String input = reader.getInput();
        input = input.trim().toLowerCase();
        return input;
    }
    
    public String computerChoice()
    {
        Random ran = new Random();
        int myRanInt = ran.nextInt(3);
        String computerRanChoice ="";
        switch(myRanInt) {
        case 0: computerRanChoice = "paper";
                break;
        case 1: computerRanChoice = "scissors";
                break;
        case 2: computerRanChoice = "rock";
                break;
    }
        return computerRanChoice;
    }
    
    public void playGame()
    
    {
        System.out.println("The computers choice is " + computerRanChoice);
        
    }

【问题讨论】:

  • 我们可以在方法playGame():final String computerChoice = computerChoice();中调用方法computerChoice()
  • 加括号:System.out.println("The computers choice is " + computerRanChoice());
  • 您尝试做的不是“从另一个方法调用方法变量”(这是不可能的),而只是捕获此方法返回的值。 String myValueReturned = computerRanChoice(); 然后在你的日志中显示这个值:System.out.println("Choice is " + myValueReturned);
  • public void playGame() { System.out.println("The computers choice is: --> " + computerChoice()); }.

标签: java class oop methods


【解决方案1】:

排序答案是在函数playGame()内部调用成员函数computerChoice()。下面有一个例子。

您似乎错过了一个游戏循环。这是一个Event Loop,可以让您的游戏一直运行,直到事件发生。

您的playGame() 函数应该实现该循环,以便轮流执行。类似的东西

    public void playGame()
    {
        while (1) 
        {
            printPrompt();
            String userMove = this.userChoice();
            String computerRanChoice = this.computerChoice();
            // Compare and set the winner
            System.out.println("The computers choice is " + computerRanChoice);
        }
 
    }

输入读取将锁定执行,直到读取某些内容。

我建议添加一个打破循环并完成游戏的用户输入。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-03
    • 2020-04-24
    • 2013-10-25
    • 1970-01-01
    • 2014-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多