import java.util.*;
public class HangManP5
{
public static void main(String[] args)
{
int attempts = 10;
int wordLength;
boolean solved;
Scanner k = new Scanner(System.in);
System.out.println("Hey, what's your name?");
String name = k.nextLine();
System.out.println(name+ ", hey! This is a hangman game!\n");
RandomWord(word);
int len = word.length();
char[] temp = new char[len];
for(int i = 0; i < temp.length; i++)
{
temp[i] = '*';
}
System.out.print("\n");
System.out.print("Word to date: ");
while (attempts <= 10 && attempts > 0)
{
System.out.println("\nAttempts left: " + attempts);
System.out.print("Enter letter: ");
String test = k.next();
if(test.length() != 1)
{
System.out.println("Please enter 1 character");
continue;
}
char testChar = test.charAt(0);
int foundPos = -2;
int foundCount = 0;
while((foundPos = word.indexOf(testChar, foundPos + 1)) != -1)
{
temp[foundPos] = testChar;
foundCount++;
len--;
}
if(foundCount == 0)
{
System.out.println("Sorry, didn't find any matches for " + test);
}
else
{
System.out.println("Found " + foundCount + " matches for " + test);
}
for(int i = 0; i < temp.length; i++)
{
System.out.print(temp[i]);
}
System.out.println();
if(len == 0)
{
break; //Solved!
}
attempts--;
}
if(len == 0)
{
System.out.println("\n---------------------------");
System.out.println("Solved!");
}
else
{
System.out.println("\n---------------------------");
System.out.println("Sorry you didn't find the mystery word!");
System.out.println("It was \"" + word + "\"");
}
}
public static String RandomWord(String word)
{
//List of words
Random r = new Random();
int a = 1 + r.nextInt(5);
if(a == 1)
{
word=("Peace");
}
if(a == 2)
{
word=("Nuts");
}
if(a == 3)
{
word=("Cool");
}
if(a == 4)
{
word=("Fizz");
}
if(a == 5)
{
word=("Awesome");
}
return (word);
}
}
좋습니다. 행맨 게임 코드입니다. 프로그램에서 단어 중 하나를 무작위로 추출하는 것이 유일한 방법입니다.이 단어는 메서드에서 성공적으로 수행해야합니다. 하지만 유일한 문제는 String 변수 "word"을 주 클래스로 돌아가는 것입니다. 메인 클래스의 모든 "word" 변수에 밑줄을 긋는 오류가 있습니다.문자열을 반환하는 방법은 무엇입니까?
목록에서 임의의 단어를 생성하는 방법이나 다른 방법으로 도움을받을 수 있다면 놀랄 것입니다.
귀하의 경우에는
, 당신은 할 필요가있다. 당신은 그 매개 변수를 사용하지 않습니다. 구문 오류가 관련 될 수 있습니다. –
Java에서 변수를 선언하는 방법을 오해 한 것 같습니다 : ' =
변수를 선언하지 않고 메서드를 호출했습니다. @ Vulcan – BuySomeChips