所以我正在为我的 java 类创建一个刽子手游戏,但是我在用字母替换单词中的下划线时遇到了麻烦。我让它用下划线打印出这个词,比如:
for(int i = 0; i < GuessWord.length(); i++) {
if (guesses[GuessWord.charAt(i) - 'a']) {
mainword.append(words[i].charAt(i));
}
else {
mainword.append("_");
}
mainword.append(" ");
}
其余的是我的代码的其余部分。我应该提到我正在使用 Netbeans IDE 7.2 并且我使用 JLayeredPane 来显示所有内容,而不是 System.out.print。谢谢!
import java.util.Random;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class MainFrame extends javax.swing.JFrame {
public MainFrame() {
initComponents();
}
//declare variables
static String SecretWord = "";
static String Letters = "";
double Result = 0;
String SetMain = null;
StringBuilder mainword = new StringBuilder();
StringBuilder gletters = new StringBuilder();
boolean[] guesses = new boolean[26];
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];
private void GoButtonActionPerformed(java.awt.event.ActionEvent evt) {
mainword.append(SecretWord);
//make word in underscore form
for(int i = 0; i < GuessWord.length(); i++) {
if (guesses[GuessWord.charAt(i) - 'a']) {
mainword.append(words[i].charAt(i));
}
else {
mainword.append("_");
}
mainword.append(" ");
}
//put in label
SetMain = mainword.toString();
WordLabel.setText(SetMain);
GuessButton.setEnabled(true);
GoButton.setEnabled(false);
}
private void GuessButtonActionPerformed(java.awt.event.ActionEvent evt) {
//declare variables
String strGuess = GuessText.getText();
String SetMain = null;
String GuessedLetters = null;
Result = 1;//(int)(Math.random() * 11) + 1;
int errors = 0;
int i = 0;
char guess2 = strGuess.charAt(i);
gletters.append(Letters);
//*******MAJOR PROBLEM AREA FOCUS HERE*******
do{
//replace underscore with guessed letter
for(i = 0; i < GuessWord.length(); i++) {
if (GuessWord.charAt(i) == guess2) {
mainword.replace(0,i,strGuess.toUpperCase());
}
else {
mainword.append("_");
}
mainword.append(" ");
}
//put in labels
SetMain = mainword.toString();
GuessedLetters = gletters.toString();
WordLabel.setText(SetMain);
GuessedLabel.setText(GuessedLetters);
GuessText.setText(null);
GuessText.requestFocusInWindow();
}//end of do
while(SetMain == null);
if (SetMain.equalsIgnoreCase(GuessWord)){
//show winning message to user and reset game
JOptionPane.showMessageDialog(null, "Congrats!");
GuessButton.setEnabled(false);
GoButton.setEnabled(true);
WordLabel.setText(null);
GuessedLabel.setText(null);
WinsLabel.setText("1");
}
//if too many errors show lost message
else if (errors >= 5){
JOptionPane.showMessageDialog(null, "You Lost!");
GuessButton.setEnabled(false);
GoButton.setEnabled(true);
WordLabel.setText(null);
GuessedLabel.setText(null);
LossesLabel.setText("1");
}
}//end of 1GAME
}
任何帮助都会很棒!请不要太复杂。我还在上面的代码中标记了我的主要问题区域。