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
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
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.