-1
我正在写一个Java hang子手游戏,到目前为止我已经得到了代码来一次替换一个。我需要的是每次都要替换,直到这个词被猜出。下面是它如何工作的一次一个:Java的hang子手如何累计添加字母
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();
所以我希望代码能够累积取代字母,也就是说,如果这话您好:
硒CRET字:_ _ _ _ _ 猜到è....
密语:_é_ _ _ 猜到Ø....
密语:_é_Ø 猜中的。 ...
密语:_é_Ø 猜^ h ....
塞里特词:他_Ø 猜到升....
密语:你好 恭喜!
我需要这个在Netbeans IDE 7.2中工作,它必须为JLayeredPane工作,而不是System.out.print方法。谢谢!
请指出您的问题。您是否希望我们编写您的游戏,以便它可以与JLayeredPane一起使用,而不是在控制台中使用? –
@tim_a,问题出在第一句话。我希望代码能够累积地替换字母,而不是一次一个。游戏在JLayeredPane的罚款。 – JavaProdigy
只是一个样式提示,在Java中,你不想大写你的变量名(除非它们是常量)。您还应该使用camelCase来处理诸如“randvalue”之类的内容(例如randValue)请查看:http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-135099.html#367。 –