Hi to All,
I am doing on a hangman project, Where this is a very simple one, where player would guess the word and if it is correct the letter would be from "-" to the correct letter once all letter is correct they system will appear out good job u clear the game.
I had done up the game and it work however i find mine is rather impractical, looking for better solution for it. please enlighten me in it.
-
public static void main(String[]agr)
-
{
-
String [] fruits ={"apple","pear","watermelon","grape","orange","banana","durian","jackfruit"};
-
-
String [] pear ={"p","e","a","r"};
-
String answer ="";
-
int chooice =(int)(Math.random ()*7);
-
-
answer = fruits[chooice];
-
if (answer.equals("apple"))
-
{
-
apple();
-
}
-
else if (answer.equals("pear"))
-
{
-
pear();
-
}
-
....
-
public static void apple()
-
{
-
Scanner sc = new Scanner(System.in);
-
String word = "";
-
String [] apple ={"-","-","-","-","-"};
-
int guess =apple.length;
-
int correct =0;
-
System.out.println("The word you pick is a Fruits which have "+apple.length+"letter");
-
System.out.println("You will have "+ apple.length +"chance to guess the word");
-
-
while ( guess>0)
-
{
-
for (int b = 0;b<apple.length;b++)
-
{
-
System.out.print(apple[b]);
-
}
-
System.out.println();
-
System.out.print("Please guess the word\t:");
-
word = sc.nextLine();
-
if (word.equals("a"))
-
{
-
apple[0]= "a";
-
correct +=1;
-
}
-
-
else if (word.equals("p"))
-
{
-
apple[1]="p";
-
apple[2]="p";
-
correct+=2;
-
}
-
.....
-
}
-
else
-
{
-
System.out.println("You have make an incorrect guess");
-
}
-
guess--;
-
System.out.println("You have left with "+guess+"guess");
-
-
if(correct ==apple.length)
-
{
-
System.out.println("You have guessed the word correctly");
-
System.out.println("You WIN");
-
break;
-
}
-
else if (guess == 0)
-
{
-
System.out.println("Sorry you have lost");
-
System.out.println("You have used up all your "+apple.length+" guess");
-
}
-
-
}
-
}
-
....
-
public static void pear()
-
{
-
...[same as the apple but will the "if" will change to match the letter]
-
}
-
After the above code[part of it] my main question would be will it be possible to have me calling only one method? rather then me having 8 method. As if i want 100 different fruits, then i would need 100 method(which to me is impractical) hence i would like to know what are the possible way to solve this problem?
if you would need to see the whole code in order to help, do tell me i will post it up
P.S. please refer me to other link if they are similar question, as there are really just too much link and i seen some other hangman problem but some are too difficult to understand. [I am currently still new to programming - java]