私はJavaの絞首刑執行人のゲームを書いていますが、これまでのところ、一度に1つずつ置き換えるコードを入手しています。私が必要としているのは、単語が推測されるまで毎回交換することです。一度に1つずつ機能する方法は次のとおりです。
for(int i = 0; i < GuessWord.length(); i++) {
foundword = words[randvalue].replaceAll("[^" + xletters + "]", "_ ");
}
GuessedLetters = xletters.toString().toUpperCase();
WordLabel.setText(foundword.toUpperCase());
GuessedLabel.setText(GuessedLetters);
GuessText.setText(null);
GuessText.requestFocusInWindow();
そして、これはあまりうまくいかなかった私の他の試みです:
//replace underscores with letters as they are guessed while the word is not solved
do {
foundword = words[randvalue].replaceAll("[^" + xletters + "]", "_ ");
}
while (!SetMain.equals(GuessWord));
//set results to labels
WordLabel.setText(foundword.toUpperCase());
GuessedLabel.setText(GuessedLetters);
GuessText.setText(null);
GuessText.requestFocusInWindow();
そして、これがそれを必要とする人々のための私のコード全体です:
import java.util.Random;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class MainFrame extends javax.swing.JFrame {
public MainFrame() {
initComponents();
}
static String SecretWord = "";
double Result = 0;
StringBuilder mainword = new StringBuilder();
String[] words = {"technology", "computer", "camera", "graphic design", "digital", "media", "technician", "photography", "troubleshoot", "pixels", "application", "download"};
Random r = new Random();
int randvalue = r.nextInt(11);
String GuessWord = words[randvalue];
int errors = 0;
private void GoButtonActionPerformed(java.awt.event.ActionEvent evt) {
for(int i = 0; i < GuessWord.length(); i++) {
mainword.append("_ ");
}
mainword.append(SecretWord);
String SetMain = mainword.toString();
WordLabel.setText(SetMain);
GuessButton.setEnabled(true);
GoButton.setEnabled(false);
}
private void GuessButtonActionPerformed(java.awt.event.ActionEvent evt){
String strGuess = GuessText.getText(); //user input
StringBuilder xletters = new StringBuilder(strGuess); // letters guessed
String GuessedLetters = null;
String foundword = null;
//replace underscores with letters as they are guessed
for(int i = 0; i < GuessWord.length(); i++) {
foundword = words[randvalue].replaceAll("[^" + xletters + "]", "_ ");
}
//set to labels to display results
GuessedLetters = xletters.toString().toUpperCase();
WordLabel.setText(foundword.toUpperCase());
GuessedLabel.setText(GuessedLetters);
GuessText.setText(null);
GuessText.requestFocusInWindow();
したがって、コードで文字を累積的に置き換えることができるようにする必要があります。つまり、単語がhelloの場合は次のようになります。
秘密の言葉:_ _ ___推測e...。
秘密の言葉:_ e ___推測o...。
秘密の言葉:_ e __o推測...
秘密の言葉:_ e __o推測されたh...。
Seret Word:彼は__o推測したl...。
秘密の言葉:こんにちはおめでとうございます!
これはNetbeansIDE7.2で機能するために必要であり、System.out.printメソッドではなく、JLayeredPaneで機能する必要があります。ありがとう!