【问题标题】:Passing a parameter to another function将参数传递给另一个函数
【发布时间】:2020-10-03 17:03:50
【问题描述】:

我为刽子手写了一个代码,我想传递随机猜测的单词(从文本文件中随机猜测),传递给函数hangman(),在那里我可以获得单词的长度。将从getRandomWord(String path) 函数中猜出一个随机词,我已将获得的值传递给function() 但似乎无法传递并得到结果。

public class Main {

    public static void main(String[] args) throws IOException {
        Main ma = new Main();
        String stm= null;

        loadWords();
        //hangman(w);
        function();

    }

    public static String[] loadWords() {

        System.out.println("Loading words from file :");

        try {
            File myObj = new File("C:\\Users\\Admin\\Documents\\NetBeansProjects\\Main\\words.txt");
            Scanner myReader = new Scanner(myObj);
            while (myReader.hasNext()) {
                String data = myReader.nextLine().toLowerCase();
                String[] spl = data.split(" ");
                System.out.println(spl.length + " words loaded");
                return spl;
            }
            myReader.close();
        } catch (FileNotFoundException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }

        return null;
        // TODO: Fill in your code here
    }

public static String getRandomWord(String path) throws IOException {
        List<String> words = new ArrayList<String>();
        try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] wordline = line.split("\\s+");
                for (String word : wordline) {
                    words.add(word);
                }
            }
        }
        Random rand = new Random();
        return words.get(rand.nextInt(words.size()));
    }

    public static List< String> getRemainingLetters(ArrayList< String> lettersGuessed) {
        String alpha = "abcdefghijklmnopqrstuvwxyz";
        String[] alpha1 = alpha.split("");
        ArrayList< String> alpha2 = new ArrayList<>(Arrays.asList(alpha1));
        for (int i = 0; i < lettersGuessed.size(); i++) {
            for (int j = 0; j < alpha2.size(); j++) {
                if (alpha2.get(j).equals(lettersGuessed.get(i))) {
                    alpha2.remove(j);
                    break;
                }
            }
        }
        return alpha2;
    }

    public static void function() throws IOException {

        int numGuesses = 5;
        String w = getRandomWord("C:\\Users\\Admin\\Documents\\NetBeansProjects\\Main\\words.txt");

        String[] word = w.split("");
        ArrayList< String> wList = new ArrayList<>(Arrays.asList(word));
        ArrayList< String> wAnswer = new ArrayList< String>(wList.size());
        for (int i = 0; i < wList.size(); i++) {
            wAnswer.add("_ ");
        }
        int left = wList.size();
        Scanner scanner = new Scanner(System.in);
        boolean notDone = true;
        ArrayList< String> lettersGuessed = new ArrayList< String>();

        while (notDone) {
            System.out.println();
            String sOut = "";

            List< String> lettersLeft = getRemainingLetters(lettersGuessed);
            for (String s : lettersLeft) {
                sOut += s + " ";
            }
            System.out.println("Letters Left: " + sOut);

            sOut = "";
            for (int i = 0; i < wList.size(); i++) {
                sOut += wAnswer.get(i);
            }
            System.out.println(sOut + " Guesses left:" + numGuesses);
            System.out.print("Enter a letter(* exit): ");
            String sIn = scanner.next();
            numGuesses--;
            if (sIn.equals("*")) {
                break;
            }
            lettersGuessed.add(sIn);
            for (int i = 0; i < wList.size(); i++) {
                if (sIn.equals(wList.get(i))) {
                    wAnswer.set(i, sIn);
                    left--;
                }
            }
            if (left == 0) {
                System.out.println("Congradulations you guessed it!");
                break;
            }
            if (numGuesses == 0) {

                StringBuilder sb = new StringBuilder();
                for (String string : wList) {
                    sb.append(string);

                }
                String stm = sb.toString();
                System.out.println("Sorry you ran out of guesses, the word was: " + stm);
                break;
            }

        }

    }

    public static void hangman(String word) {

        System.out.println("Welcome to Hangman Ultimate Edition");
        System.out.println("I am thinking of a word that is " + word.length() + " letters long");
        System.out.println("-------------");


    }
}

【问题讨论】:

  • 你必须调用函数来传递值或创建一个全局变量
  • 这将是调试器的完美使用。
  • @Eklavya 你能举个例子吗?
  • @chinthanadissanayake 向我们展示完整的代码,然后我们就可以了。你在任何地方打电话给hangman 吗?
  • @Eklavya - 我已经更新了上面的完整代码。我只是从public static void main (String args []) 打电话给hangman(),而不是从其他任何地方。但正确的输出没有出现所以我评论了public static void main (String args [])hangman()

标签: java arraylist parameter-passing


【解决方案1】:

要使现有代码运行,您只需清理 main 方法:

  • 删除未使用的代码:
Main ma = new Main(); // no need to create an instance, you use only static methods
String stm= null;     // not used anywhere
loadWords();          // not used, entire method may be removed:
                      // it reads words only in the first line
  • 修复方法function 有一个String w 参数,将随机词移出该方法。

因此,产生的变化应该是:

public static void main(String[] args) throws IOException {
    String word = getRandomWord("C:\\Users\\Admin\\Documents\\NetBeansProjects\\Main\\words.txt");
    hangman(word);
    function(word);
}

public static void function(String w) throws IOException {

    int numGuesses = 5;

    String[] word = w.split("");
// ... the rest of this method remains as is
}

【讨论】:

    【解决方案2】:

    代码中的问题:

    1. 不将随机词传递给方法hangmanfunction
    2. 您没有在main 中重新使用从方法获得的随机词getRandomWord,而是在方法getRandomWord 中再次调用getRandomWord,这将为您提供一个不同的随机词,从而导致不一致。

      下面给出的是带有示例运行的更正程序:

      import java.io.BufferedReader;
      import java.io.FileReader;
      import java.io.IOException;
      import java.util.ArrayList;
      import java.util.Arrays;
      import java.util.List;
      import java.util.Random;
      import java.util.Scanner;
      
      public class Main {
          public static void main(String[] args) throws IOException {
              String word = getRandomWord("C:\\Users\\Admin\\Documents\\NetBeansProjects\\Main\\words.txt");
              hangman(word);
              function(word);
          }
      
          public static String getRandomWord(String path) throws IOException {
              List<String> words = new ArrayList<String>();
              try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
                  String line;
                  while ((line = reader.readLine()) != null) {
                      String[] wordline = line.split("\\s+");
                      for (String word : wordline) {
                          words.add(word);
                      }
                  }
              }
              Random rand = new Random();
              return words.get(rand.nextInt(words.size()));
          }
      
          public static List<String> getRemainingLetters(ArrayList<String> lettersGuessed) {
              String alpha = "abcdefghijklmnopqrstuvwxyz";
              String[] alpha1 = alpha.split("");
              ArrayList<String> alpha2 = new ArrayList<>(Arrays.asList(alpha1));
              for (int i = 0; i < lettersGuessed.size(); i++) {
                  for (int j = 0; j < alpha2.size(); j++) {
                      if (alpha2.get(j).equals(lettersGuessed.get(i))) {
                          alpha2.remove(j);
                          break;
                      }
                  }
              }
              return alpha2;
          }
      
          public static void function(String w) throws IOException {
              // The available number of guesses = length of the random word
              int numGuesses = w.length();
      
              // Split the random word into letters
              String[] word = w.split("");
      
              ArrayList<String> wList = new ArrayList<>(Arrays.asList(word));
              ArrayList<String> wAnswer = new ArrayList<String>(wList.size());
      
              for (int i = 0; i < wList.size(); i++) {
                  wAnswer.add("_ ");
              }
      
              int left = wList.size();
              Scanner scanner = new Scanner(System.in);
              boolean notDone = true;
              ArrayList<String> lettersGuessed = new ArrayList<String>();
      
              while (notDone) {
                  System.out.println();
                  String sOut = "";
      
                  List<String> lettersLeft = getRemainingLetters(lettersGuessed);
                  for (String s : lettersLeft) {
                      sOut += s + " ";
                  }
                  System.out.println("Letters Left: " + sOut);
      
                  sOut = "";
                  for (int i = 0; i < wList.size(); i++) {
                      sOut += wAnswer.get(i);
                  }
                  System.out.println(sOut + " Guesses left:" + numGuesses);
                  System.out.print("Enter a letter(* exit): ");
                  String sIn = scanner.next();
                  numGuesses--;
                  if (sIn.equals("*")) {
                      break;
                  }
                  lettersGuessed.add(sIn);
                  for (int i = 0; i < wList.size(); i++) {
                      if (sIn.equals(wList.get(i))) {
                          wAnswer.set(i, sIn);
                          left--;
                      }
                  }
                  if (left == 0) {
                      System.out.println("Congradulations you guessed it!");
                      break;
                  }
                  if (numGuesses == 0) {
      
                      StringBuilder sb = new StringBuilder();
                      for (String string : wList) {
                          sb.append(string);
      
                      }
                      String stm = sb.toString();
                      System.out.println("Sorry you ran out of guesses, the word was: " + stm);
                      break;
                  }
              }
          }
      
          public static void hangman(String word) {
              System.out.println("Welcome to Hangman Ultimate Edition");
              System.out.println("I am thinking of a word that is " + word.length() + " letters long");
              System.out.println("-------------");
          }
      }
      

      示例运行:

              Welcome to Hangman Ultimate Edition
      I am thinking of a word that is 3 letters long
      -------------
      
      Letters Left: a b c d e f g h i j k l m n o p q r s t u v w x y z 
      _ _ _  Guesses left:3
      Enter a letter(* exit): c
      
      Letters Left: a b d e f g h i j k l m n o p q r s t u v w x y z 
      _ _ _  Guesses left:2
      Enter a letter(* exit): a
      
      Letters Left: b d e f g h i j k l m n o p q r s t u v w x y z 
      _ _ _  Guesses left:1
      Enter a letter(* exit): t
      Sorry you ran out of guesses, the word was: fox
      

    【讨论】:

      猜你喜欢
      • 2012-09-25
      • 2014-01-06
      • 2019-10-09
      • 1970-01-01
      • 2018-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多