The "randomword" can not access the .length method. Why is that?

55 views Asked by At

I am trying to make a hangman game and I have a problem with finding the length of the random word chosen automatically

import java.util.Scanner;
import java.util.Random;

public class Main {

    public static void main(String[] args) {
        Random rand = new Random(); 
        int upperbound = 40; 
        int int_random = rand.nextInt(upperbound); 
        
        Dictionary S1 = new Dictionary();
        S1.printInfo(); 
        Dictionary randomword = new Dictionary();
        randomword.getWord(int_random); 
        
        char[] letters = new char[(randomword.length)];
        int lives = 8;
        Scanner answer = new Scanner(System.in);
        
        while (lives > 0) {
            
            //System.out.println("The random word is now: " +);
            System.out.println("You have" + lives + "guesses left.");
        
            for(int i= 0; i < lives; i++) {
                System.out.println("0") ;
            }
        
            System.out.println("Your guess:");
            String guess = answer.nextLine();
            char letter = guess.charAt(0);
        }
    }
}
public class Dictionary {

    public String getWord(int index) {
        switch (index) {
        case 0: return "UNIVERSITY";
        ...
        default: return "Illegal index";
        }
    }   

I was expecting to be able to use .length in "randomword" but i can not

2

There are 2 answers

0
Arfur Narf On

A Dictionary does not have a length method. A Dictionary can give you a String that has a length method.

You call getWord on the Dictionary, which returns a String, which would have a length. But you didn't retain the String, so you can't ask it for its length.

Maybe you meant

Dictionary dict = new Dictionary();
String randomword = dict.getWord(int_random);   
char[] letters = new char[randomword.length()];

Note that the length of a String is fetched by a method call, not as a direct read of a field. That is, parentheses are required after the name.

This has better names, given that a 'Dictionary' is not actually a 'word'. Good naming is half the battle when it comes to understanding program code.

0
Reilas On

Here is an example.

class Dictionary {
    Random r = new Random();
    List<String> l = new ArrayList<>();

    Dictionary() {
        l.add("UNIVERSITY");
        l.add("COLLEGE");
        l.add("ACADEMY");
    }

    String randomWord() {
        return l.get(r.nextInt(l.size()));
    }

    void printInfo() {
        System.out.println(this);
    }

    @Override
    public String toString() {
        return "{ l = %s }".formatted(l);
    }
}
Dictionary d = new Dictionary();
String s = d.randomWord();
int n = s.length();