I recently started learning programming and in particular Java. I wrote this small hangman game which takes the input for the secret word from the user.
It all works as intended; I would like to know ways to optimize or improve this code (taking into account that the input must be taken from the user and not from a file).
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Write the word");
String word = sc.nextLine();
List<String> wordSeg = new ArrayList<>(word.length());
for (int x = 0; x < word.length(); x++) {
wordSeg.add("*");
}
int i = 0;
int chancesLeft;
String usedCharacters = "";
while (i < 6) {
chancesLeft = 6 - i;
System.out.println("Write a character or a word");
String character = sc.nextLine();
char characterChar = character.charAt(0);
if (character.equals(word)){
System.out.println("You won!");
break;
}
else if (word.contains(Character.toString(characterChar)) && character.length() < 2){
for (int indx = 0; indx < word.length(); indx++){
if (word.charAt(indx) == characterChar) {
wordSeg.set(indx, character);
}
}
System.out.print(wordSeg);
continue;
} else {
usedCharacters = character + " - " + usedCharacters;
}
i++;
System.out.println("Chances left: " + chancesLeft);
System.out.println("Characters not included: " + usedCharacters);
}
}
}
```