向另一个函数传递参数

问题描述 投票:0回答:1

我为刽子手写了一段代码,我想把随机猜出的单词(从文本文件中随机猜出的),传递给一个函数。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("-------------");


    }
}
java arraylist parameter-passing
1个回答
0
投票

你的代码中存在的问题。

  1. 没有把随机词传给方法。hangmanfunction.
  2. 而不是重复使用该方法得到的随机词。getRandomWordmain,你已经打电话 getRandomWord 再在方法中。hangman 这将给你一个不同的随机词导致不一致。

    下面给出的是修正后的程序与运行示例。

    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
    

0
投票

为了使你现有的代码能够运行,你只需要清理一下... ... 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
}
© www.soinside.com 2019 - 2024. All rights reserved.