How to return a string?

前端 未结 2 607
遥遥无期
遥遥无期 2021-01-14 23:11
import java.util.*;
public class HangManP5 
{
public static void main(String[] args) 
{
int attempts = 10;
int wordLength;
boolean solved;
Scanner k = new Scanner(Sy         


        
相关标签:
2条回答
  • 2021-01-14 23:26

    In java, parameters are passed by value and not by reference. Therefore, you cannot change the reference of a parameter.

    In your case, you need to do:

    public static String getRandomWord() {
        switch(new Random().nextInt(5)) {
            case 0:
                return "Peace";
            case 1:
                return "Nuts";
            // ...
            default:
                throw new IllegalStateException("Something went wrong!");
        }
    }
    

    And in main:

    // ...
    String word = getRandomWord();
    int len = word.length(); 
    // ...
    
    0 讨论(0)
  • 2021-01-14 23:31

    You can't modify the caller's reference.

    RandomWord(word);
    

    needs to be something like

    word = RandomWord(word);
    

    Also, by convention, Java methods start with a lower case letter. And, you could return the word without passing one in as an argument and I suggest you save your Random reference and use an array like

    private static Random rand = new Random();
    public static String randomWord() {
        String[] words = { "Peace", "Nuts", "Cool", "Fizz", "Awesome" };
        return words[rand.nextInt(words.length)];
    }
    

    And then call it like

    word = randomWord();
    
    0 讨论(0)
提交回复
热议问题