Jeg skrev dette hangman-program. Det tager tre ord i en matrix, vælger et tilfældigt ord, og derefter gætter brugeren bogstaverne. Det er langvarigt, men det er ekstremt simpelt og forståeligt. Forslag er velkomne, men husk, min viden i java er begrænset.

import java.util.*; public class Hangman { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int noOfGuesses =0,lettersCorrect=0; String choiceToPlay, userGuess; char menuChoice, letter; String[] list={"hello","java","loop"}; System.out.println("\t\t\t\tWelcome to Hangman!");//main game start menu System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); do { System.out.println("\t\t\t Do you want to play? Press Y/N\n"); choiceToPlay = sc.next(); menuChoice = choiceToPlay.charAt(0); if(!(menuChoice == "y"||menuChoice == "Y"||menuChoice == "n"||menuChoice =="N")) { System.out.println("\t\t\t\tYou have entered an invalid option. Try again!\n"); }//if any letter other than y or n is entered }//do while (!(menuChoice =="Y" ||menuChoice=="y"||menuChoice == "n"|| menuChoice =="N")); if(menuChoice == "N"||menuChoice =="n") { System.out.println("You have chosen to leave the game."); System.out.println("Goodbye!"); System.exit(0); }//if else { int randomWordNumber = (int)((Math.random()*list.length));// Pick random index of guessWord array char[] enteredLetters = new char[list[randomWordNumber].length()];// Create an array to store already entered letters switch(randomWordNumber) { case 1: { char [] correctLetter = {"-", "-", "-", "-", "-"}; while(lettersCorrect <5) { char guessWord[]={"h","e","l","l","o"}; System.out.println("\nThe guess word has 5 letters."); System.out.println("Enter a letter to guess: "); userGuess = sc.next(); letter = userGuess.charAt(0);//Incrementing letters each time. noOfGuesses++; if(letter == guessWord[0]) { System.out.println("There is 1 "+guessWord[0]+" in the word"); System.out.println("You have guessed the first letter correctly."); correctLetter[0] = letter; System.out.println(correctLetter); System.out.println("You have had " + noOfGuesses + " guesses, so far"); lettersCorrect++; System.out.println("Letters correct so far: "+lettersCorrect); }//if first letter else if(letter==guessWord[1]) { System.out.println("There is 1 "+guessWord[1]+" in the word"); System.out.println("You have guessed the second letter correctly."); correctLetter[1] = letter; System.out.println(correctLetter); System.out.println("You have had " + noOfGuesses + " guesses, so far"); lettersCorrect++; System.out.println("Letters correct so far: "+lettersCorrect); }//if second letter else if(letter ==guessWord[2]||letter==guessWord[3]) { System.out.println("There are 2 "+guessWord[2]+" in the word"); System.out.println("You have guessed the third and fourth letters correctly."); correctLetter[2] = letter; correctLetter[3]=letter; System.out.println(correctLetter); System.out.println("You have had " + noOfGuesses + " guesses, so far"); lettersCorrect+=2; System.out.println("Letters correct so far: "+lettersCorrect); }//if third and fourth letters else if(letter ==guessWord[4]) { lettersCorrect++; System.out.println("There is 1 O in the word"); System.out.println("You have guessed the fifth letter correctly."); correctLetter[4] = letter; System.out.println(correctLetter); System.out.println("You have had " + noOfGuesses + " guesses, so far"); System.out.println("Letters correct so far: "+lettersCorrect); }//if fifth letter else { System.out.println("The letter you guessed is not in the word.\n"); System.out.println("Guesses taken so far: "+noOfGuesses); System.out.println("Letters correct so far: "+lettersCorrect); }//else incorrect letter } System.out.println("\nYou found the word!"); System.out.println("It was hello."); System.out.println("Total guesses: "+noOfGuesses); break; } case 2: { char [] correctLetter = {"-", "-", "-", "-"}; while(lettersCorrect <4) { char guessWord[]={"j","a","v","a"}; System.out.println("\nThe guess word has 4 letters."); System.out.println("Enter a letter to guess: "); userGuess = sc.next(); letter = userGuess.charAt(0);//Incrementing letters each time. noOfGuesses++; if(letter == guessWord[0]) { System.out.println("There is 1 "+guessWord[0]+" in the word"); System.out.println("You have guessed the first letter correctly."); correctLetter[0] = letter; System.out.println(correctLetter); System.out.println("You have had " + noOfGuesses + " guesses, so far"); lettersCorrect++; System.out.println("Letters correct so far: "+lettersCorrect); }//if first letter else if(letter==guessWord[1]) { System.out.println("There are 2 "+guessWord[1]+" in the word"); System.out.println("You have guessed the second and fourth letters correctly."); correctLetter[1] = letter; correctLetter[3] = letter; System.out.println(correctLetter); System.out.println("You have had " + noOfGuesses + " guesses, so far"); lettersCorrect+=2; System.out.println("Letters correct so far: "+lettersCorrect); }//if second letter else if(letter ==guessWord[2]) { System.out.println("There is 1 "+guessWord[2]+" in the word"); System.out.println("You have guessed the third letter correctly."); correctLetter[2] = letter; System.out.println(correctLetter); System.out.println("You have had " + noOfGuesses + " guesses, so far"); lettersCorrect++; System.out.println("Letters correct so far: "+lettersCorrect); }//if third and fourth letters else { System.out.println("The letter you guessed is not in the word.\n"); System.out.println("Guesses taken so far: "+noOfGuesses); System.out.println("Letters correct so far: "+lettersCorrect); }//else incorrect letter }//while loop System.out.println("\nYou found the word!"); System.out.println("It was java."); System.out.println("Total guesses: "+noOfGuesses); break; } default: { char [] correctLetter = {"-", "-", "-", "-"}; while(lettersCorrect<4) { char guessWord[]={"l","o","o","p"}; System.out.println("\nThe guess word has 4 letters."); System.out.println("Enter a letter to guess: "); userGuess = sc.next(); letter = userGuess.charAt(0);//Incrementing letters each time. noOfGuesses++; if(letter == guessWord[0]) { System.out.println("There is 1 "+guessWord[0]+" in the word"); System.out.println("You have guessed the first letter correctly."); correctLetter[0] = letter; System.out.println(correctLetter); System.out.println("You have had " + noOfGuesses + " guesses, so far"); lettersCorrect++; System.out.println("Letters correct so far: "+lettersCorrect); }//if first letter else if(letter==guessWord[1]) { System.out.println("There are 2 "+guessWord[1]+" in the word"); System.out.println("You have guessed the second and third letters correctly."); correctLetter[1] = letter; correctLetter[2] = letter; System.out.println(correctLetter); System.out.println("You have had " + noOfGuesses + " guesses, so far"); lettersCorrect+=2; System.out.println("Letters correct so far: "+lettersCorrect); }//if second letter else if(letter ==guessWord[3]) { System.out.println("There is 1 "+guessWord[3]+" in the word"); System.out.println("You have guessed the fourth letter correctly."); correctLetter[3]=letter; System.out.println(correctLetter); System.out.println("You have had " + noOfGuesses + " guesses, so far"); lettersCorrect++; System.out.println("Letters correct so far: "+lettersCorrect); }//if third and fourth letters else { System.out.println("The letter you guessed is not in the word.\n"); System.out.println("Guesses taken so far: "+noOfGuesses); System.out.println("Letters correct so far: "+lettersCorrect); }//else incorrect letter }//while loop }//case System.out.println("\nYou found the word!"); System.out.println("It was loop."); System.out.println("Total guesses: "+noOfGuesses); }//switch } } } 

Svar

Din kode er ret ligetil og let at følge. Der er flere ting, du kan gøre, hvoraf nogle har jeg foreslået nedenfor for at gøre det lettere at opdatere og danne et grundlag for fremtidige programmer.

main

You ” har skrevet al din kode i hovedfunktionen. Dette er en ret typisk tilgang for folk, der lærer sproget. Du fortsætter med at tilføje logikken efter behov, indtil du kommer til slutningen. Det kan hurtigt blive svært at udvide eller opdatere. Ideelt set vil du opdele hovedet i logiske elementer (andre klasser & funktioner), der kan forbindes til at danne dit program. Hvert element skal have et særskilt ansvar og bør navngives i overensstemmelse hermed. Dette vil gøre de enkelte elementer lettere at forstå og gøre det lettere at identificere kandidater til genbrug i fremtiden.

Fjern duplikering

Du har skrevet en masse kode. En masse det er dog meget lig andre bits. Hvor du bemærker duplikering, er det ofte et godt tegn på, at du mangler en byggesten (såsom en funktion). Når du ser på din kode, kan du bryde koden op i en struktur som denne:

playAgain = askPlayerIfTheyWantToPlayAgain() if(playAgain) { wordToGuess = getRandomWord(); guessLettersUntilWin(wordToGuess); } 

Du vil bemærke, at jeg har indgået sagserklæringerne for hver ord til en enkelt metode guessLettersUntilWin, som jeg overfører ordet til. Det skyldes, at der er meget duplikering mellem de forskellige sagserklæringer, som du burde være i stand til at fjerne. Du kan bruge wordToGuess.length() for at få længden af ordet til at gætte for eksempel, snarere end hårdkodning af værdien (4/5). I stedet for hårdkodning af bogstaverne for ordet at gætte kan du bruge wordToGuess.toCharArray() osv.

Indlejring

For mange indlejringsniveauer er dårlige. De får koden til at vandre over siden til højre, indtil den falder uden for kanten af din skærm. Du kan undgå overdreven indlejring ved at bryde din kode på passende metoder. Du kan også undgå at bruge det, når det ikke er nødvendigt. For eksempel ved starten af dit program gør du:

if(menuChoice == "N"||menuChoice =="n") { System.out.println("You have chosen to leave the game."); System.out.println("Goodbye!"); System.exit(0); }//if else { // Rest of code 

Og så er resten af koden indeholdt i else klausul. if -grenen undgår aldrig, så du behøver ikke det andet. Du kan bare gøre:

if(menuChoice == "N"||menuChoice =="n") { System.out.println("You have chosen to leave the game."); System.out.println("Goodbye!"); System.exit(0); } // Rest of code 

} // kommentarer

Du ser typisk ikke mange kommentarer til lukning af seler, der indikerer, hvorfor bøjlen blev åbnet, det tilføjer bare rod til koden. De kan være nyttige, hvor du har store blokke af indlejret kode, men som jeg har sagt ovenfor, er dette ofte en indikation af, at du skal bryde din kode mere op.

sløjfer kan være din ven

Dine sagserklæringer igen, har en masse dobbeltarbejde i dem. Dette skyldes, at du har oprettet en if / else-kæde for hvert bogstav i ordet. Denne struktur kunne erstattes med en for loop (pseudocode):

for(index=0 to guessWord.length()) { if(letter == guessWord[index]) { print("You found...") lettersCorrect++; } } // check if lettersCorrect == guessWord.length() 

Skriv et svar

Din e-mailadresse vil ikke blive publiceret. Krævede felter er markeret med *