简体   繁体   English

在java程序中创建方法

[英]creating a method in a java program

I can't seem to figure out how to declare these methods without running into some kind of compiling error with the hiddenexpression.我似乎无法弄清楚如何声明这些方法而不会遇到隐藏表达式的某种编译错误。 The first method about creating the game I have is fine.关于创建我拥有的游戏的第一种方法很好。 I left it in a non-method format so it can compile.我将它保留为非方法格式,以便它可以编译。 Any tips would be great!任何提示都会很棒!

package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {

    Scanner scnr = new Scanner(System.in);

    String expr, player1Name, String player2Name;
    int player1NumGuesses = 0, player2NumGuesses = 0;

    System.out.println("Player 1, what is your name?");

    player1Name = scnr.nextLine();

    System.out.println("Player 2, what is your name?");
    player2Name = scnr.nextLine();

    System.out.println("Player 1 will be the contestant first and player 2 will be the challenger.");

    System.out.println("Then you will change roles for the second round.");
//Method 1: Replace for loop with two calls to playGame, switching     //    contestant and challenger after 1st game


    for (int j = 1; j <= 2; j++) {
        System.out.println("Contestant, turn away from the computer");
        System.out.println("Challenger, type an expression to be guessed.");
        expr = scnr.nextLine();

   //Method 2:make phrase hidden 


        StringBuffer hiddenExpr = new StringBuffer(expr);
        for (int i = 0; i < expr.length(); i++) 
            if (expr.charAt(i) == '\'' || expr.charAt(i) == ' ')
                hiddenExpr.setCharAt(i, expr.charAt(i));
            else
                hiddenExpr.setCharAt(i, '*');

                System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
        System.out.println("Contestant, here is your clue:");
        boolean guessed = false;
        int numGuesses = 0;
        char characterGuess;
        boolean found;
        String exprGuess;
        while (guessed == false && numGuesses < 26) {
            System.out.println(hiddenExpr);
            System.out.println("Contestant, guess a character");
            characterGuess = scnr.nextLine().charAt(0);
            numGuesses++;


     //Method 3, checkForCharacter:


            found = false;
            for (int i = 0; i < expr.length(); i++) {
                if (expr.charAt(i) == characterGuess) {
                    hiddenExpr.setCharAt(i, characterGuess);
                    found = true;
                }
            }
            if (found && expr.equals(hiddenExpr.toString())) {
                System.out.println("You've got the whole thing!");
                if (j == 1)
                    player1NumGuesses = numGuesses;
                else
                    player2NumGuesses = numGuesses;
                guessed = true;
            }


            else if (found) {

                System.out.println("Good for you!! That letter is in the expression.");
                System.out.println("This is what you have so far:");
                System.out.println(hiddenExpr);
                System.out.println("Guess the whole expression");
                exprGuess = scnr.nextLine();
                if (exprGuess.equals(expr)) {
                    System.out.println("You're right!");
                    if (j == 1)
                        player1NumGuesses = numGuesses;
                    else
                        player2NumGuesses = numGuesses;
                    guessed = true;
                }


                else
                    System.out.println("No, you didn't guess the right expression.");
            }
            else
                System.out.println("No, that character is not in the expression.");
        } //End while loop guessing up to 26 times
    } //End for loop going 2 times, to let each contestant have a turn


    System.out.println("Player 1 took " + player1NumGuesses + " guesses.");
    System.out.println("Player 2 took " + player2NumGuesses + " guesses.");
    if (player1NumGuesses < player2NumGuesses) 
        System.out.println("Player 1 wins!") 
    else if (player2NumGuesses < player1NumGuesses) 
        System.out.println("Player 2 wins!");
    else System.out.println("It's a tie!");
} //End main
}  //End program

My take at it.我的看法。

package com.company;
import java.util.Scanner;

public class Main {
    public static String hiddenExpression(String hidden){

        StringBuffer hiddenExpr = new StringBuffer(hidden);

        for (int i = 0; i < hidden.length(); i++)
            if (hidden.charAt(i) == '\'' || hidden.charAt(i) == ' ')
                hiddenExpr.setCharAt(i, hidden.charAt(i));
            else {
                hiddenExpr.setCharAt(i, '*');

                System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
            }return null;}
    public static void  checkChar(char characterGuess){
        Scanner scnr = new Scanner(System.in);
        boolean guessed = false;
        String expr="";

        int numGuesses = 0;
        int numguesses_contestant;

        boolean found;
        String exprGuess;
        String hiddenExpr = hiddenExpression(expr);
        numGuesses++;
        found = false;
       for (int i = 0; i < expr.length(); i++) {
           if (expr.charAt(i) == characterGuess) {
          hiddenExpression(expr);
               found = true;
            }

        if (found && expr.equals(hiddenExpr.toString())) {
            System.out.println("You've got the whole thing!");
            if (i == 1)
                numguesses_contestant = numGuesses;

        } else if (found) {
            System.out.println("Good for you!! That letter is in the expression.");
            System.out.println("This is what you have so far:");
            System.out.println(hiddenExpr);
            System.out.println("Guess the whole expression");
            exprGuess = scnr.nextLine();
            if (exprGuess.equals(expr)) {
                System.out.println("You're right!");
                if (i == 1)
                    numguesses_contestant = numGuesses;

            } else
                System.out.println("No, you didn't guess the right expression.");
        } else
            System.out.println("No, that character is not in the expression.");

    }}

//------------------------------------------------------------------------------------------------------------------//


    public  static int playGame(String contestant, String challenger, int numGuesses) {
        Scanner scnr= new Scanner(System.in);
        boolean guessed = true;
        String expr;

        int numguesses_contestant=0;
        for (int j = 0; j <= 1; j++) {
            System.out.println("Contestant, turn away from the computer");
            System.out.println("Challenger, type an expression to be guessed.");
            expr = scnr.nextLine();

           hiddenExpression(expr);

            System.out.println("Contestant, here is your clue:");

            while (guessed == false && numGuesses < 26) {
                boolean hiddenExpr=false ;
                System.out.println(hiddenExpr);
                System.out.println("Contestant, guess a character");
                char characterGuess = scnr.nextLine().charAt(0);
                numGuesses++;

                checkChar(characterGuess);

            } //End while loop guessing up to 26 times
        } //End for loop going 2 times, to let each contestant have a turn
    return numguesses_contestant; }
    //--------------------------------------------------------------------------------------------------------------------
     public static void main(String[] args) {Scanner scnr = new     Scanner(System.in);
        String player1;
        String player2;
        int n=0;
        int m =0;
        System.out.println("Welcome to Wheel of Fortune.");
        System.out.println("Player 1 enter your name");
        player1 = scnr.nextLine();
        System.out.println("Player 2 enter your name");
        player2=scnr.nextLine();
        playGame(player1, player2, n);
        playGame(player2, player1, m);

        if (n>m) {
            System.out.println(player1 + " wins!");
        }
        else if (n==m) {
            System.out.println("It's a tie!");}
        else{
            System.out.println(player2 + " wins!");
        }
    }
}

EDIT: for methods编辑:对于方法

  1. playGame This method takes as input the names of the contestant and challenger and has them play a game. playGame 此方法将参赛者和挑战者的姓名作为输入,并让他们玩游戏。 Thus, you need to call this method twice, allowing each player to guess an expression.因此,您需要调用此方法两次,让每个玩家猜测一个表达式。 This replaces the for loop that executes twice.这取代了执行两次的 for 循环。

  2. makeHiddenExpression This method takes the expression typed in by the challenger and makes another "hidden expression" by putting asterisks (*) where there are letters. makeHiddenExpression 该方法采用挑战者输入的表达式,并通过在有字母的地方放置星号 (*) 来制作另一个“隐藏表达式”。

  3. checkForCharacter This methods checks to see if a guessed character is in the expression, inserts it in the hidden expression everywhere it should be, and returns true if the character was found. checkForCharacter 该方法检查表达式中是否存在猜测的字符,将其插入到隐藏表达式中应该出现的任何位置,如果找到该字符则返回 true。

There are two problems with your code.您的代码有两个问题。 The first is in line 6.第一个在第 6 行。

String expr, player1Name, String player2Name; cannot compile.无法编译。 It should be: String expr, player1Name, player2Name;应该是: String expr, player1Name, player2Name;

The second is in line 78. You forgot the semicolon.第二个在第 78 行。你忘记了分号。

When a code doesn't compile, it's a good idea to look at the type of error message(s) and what line(s) of code the error(s) are on.当代码无法编译时,最好查看错误消息的类型以及错误所在的代码行。 Error messages are there to give you an idea of what's going on and where the problem is.错误消息是为了让您了解发生了什么以及问题出在哪里。

Suggestions:建议:

  • The meat of your code will be in your playGame method.您的代码的主要内容将在您的 playGame 方法中。
  • Don't pass in n or m into your methods as that is useless and will not change n or m 's values in the main method.不要将nm传递到您的方法中,因为这是无用的,并且不会更改主方法中nm的值。
  • Have the playGame return an int (you do that), but don't ignore the int returned!让 playGame 返回一个 int(你这样做),但不要忽略返回的 int! Set it equal to an int variable so you can compare the scores of the two players.将它设置为一个 int 变量,以便您可以比较两个玩家的分数。 ie, int n = playGame(player1, player2);即, int n = playGame(player1, player2);
  • It looks like your playGame method will need to do user interaction -- you might want to also pass your Scanner object into this method so you don't create multiple Scanners.看起来您的 playGame 方法需要进行用户交互——您可能还想将您的 Scanner 对象传递到此方法中,这样您就不会创建多个 Scanner。 This may not be completely necessary, but is something I would do.这可能不是完全必要的,但我会这样做。
  • The hiddenExpression(...) method should have no System.out.println(...) statements within it. hiddenExpression(...)方法中不应包含System.out.println(...)语句。 It should create and return a String and that's it.它应该创建并返回一个字符串,就是这样。 The playGame method will call this method, assign its result to a String variable, and thenwill then display its result within a println statement. playGame 方法将调用此方法,将其结果分配给一个 String 变量,然后将其结果显示在 println 语句中。 Alternatively, you could have the playGame method call System.out.println(hiddenExpression(challengerExpression));或者,您可以让 playGame 方法调用System.out.println(hiddenExpression(challengerExpression)); . .
  • The checkChar method should not be using a Scanner at all. checkChar 方法根本不应该使用 Scanner。
  • It should not have any println's within it.它不应该包含任何 println 。
  • All it should do is to check if the char passed within it is an as-yet unguessed char, it should update a static class field, hiddenExpression, so that it displays the char if it is in fact an unguessed char (but it should not display the hiddenExpression), and it should return true or false depending on if the char passed into it is an as yet unguessed char.它应该做的就是检查其中传递的字符是否是尚未猜测的字符,它应该更新静态类字段 hiddenExpression,以便它显示该字符,如果它实际上是未猜测的字符(但它不应该显示 hiddenExpression),它应该返回 true 或 false,具体取决于传入它的字符是否是尚未猜测的字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM