我为刽子手游戏编写了代码,该游戏从文本文件中加载猜测的短语。但是当您在控制台中输入正确的字母时,它不响应。 我正在寻找的是当你输入一个更新的正确信件时 这个 **** * 到这个 **** a *** 。 以下是我正在使用的两个课程。
import java.util.*;
import java.io.*;
public class Application {
private ArrayList<Pirateword> piratewords;
private Scanner input;
Pirateword secretWord;
private int attempts = 10;
public Application(){
input=new Scanner(System.in);
piratewords=new ArrayList<Pirateword>();
}
public void runApplication() throws IOException {
load("piratewords.txt");
hangman();
}
public void load(String fileName) throws IOException{
Scanner infile =new Scanner(new InputStreamReader(new FileInputStream(fileName)));
int num=infile.nextInt();infile.nextLine();
for (int i=0;i<num;i++) {
String w=infile.nextLine();
Pirateword p=new Pirateword(w);
piratewords.add(p);
}
infile.close();
}
public void hangman() {
Collections.shuffle(piratewords);
secretWord = piratewords.get(0);
int len = secretWord.length(); //Store the length which will be used to see if puzzle was solved.
char[] temp = new char[len]; //Store a temp array which will be displayed to the user
for(int i = 0; i < temp.length; i++) //initialize the array
{
if(secretWord.charAt(i)!= ' '){
temp[i] = '*';
}
else
{
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 = input.next();
if(test.length() != 1)
{
System.out.println("Please enter 1 character");
continue;
}
char testChar = test.charAt(0);
//Find matches
int foundPos = -2;
int foundCount = 0; //How many matches did we find
while((foundPos = secretWord.indexOf(testChar, foundPos + 1)) != -1)
{
temp[foundPos] = testChar; //Update the temp array from * to the correct character
foundCount++;
len--; //Decrease overall counter
}
if(foundCount == 0)
{
System.out.println("Sorry, didn't find any matches for " + test);
}
else
{
System.out.println("Found " + foundCount + " matches for " + test);
}
//Print
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 \"" + secretWord + "\"");
}
}
}
import java.util.*;
public class Pirateword {
private String word;
public Pirateword(String w) {
word=w;
}
public String toString(){
return word;
}
public int length(){
return word.length();
}
public char charAt(int i) {
return word.charAt(i);
}
public int indexOf(char guess, int i) {
return word.indexOf(guess);
}
}
答案 0 :(得分:2)
您的问题在于此方法indexOf
,您不使用第二个参数,即开始搜索区域的索引。
public int indexOf(char guess, int i) {
return word.indexOf(guess, i);
}
同样foundPos
应该初始化为-1。