gpt4 book ai didi

java - (索引越界)我用java写了一个刽子手游戏程序

转载 作者:行者123 更新时间:2023-12-02 11:57:21 25 4
gpt4 key购买 nike

我确信我的程序还有很多其他问题,但我目前陷入这个问题并专注于首先解决这个问题。我的目标是根据输入的单词数量循环游戏,同时改变游戏编号。我的问题是“显示横幅”部分一直循环,直到遇到“超出边界”错误。当我输入“java Hangman 123 test”时,它显示以下内容:

========
Game: 1
========
Game: 2
========
Game: 3
========
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3 at Hangman.main(Hangman.java:121)

这是我的程序:

import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
import java.util.Scanner;

public class Hangman {

//validation of raw questions
public static boolean isValidQuestion(String rawQuestion){
rawQuestion = rawQuestion.toUpperCase();
boolean vQuestion = true;
for(int i=0; i<rawQuestion.length(); i++){
char c = rawQuestion.charAt(i);

if(!(c>='A' && c<='Z'))
vQuestion = false;
}
return vQuestion;
}

//show invalid tries
public static String formatCharArray(char[] ca){
String output = "";
for(int i=0; i<ca.length; i++){
output += ca[i] + " ";
}
return output;
}

public static void main(String args[]){

if(args.length==0){
System.out.println("Usage: java Hangman word_to_guess [more_word_to_quess]...");
return;
}

List<String> validQuestions = new ArrayList<>();
for (int i = 0; i < args.length; i++){
String rawQuestion = args[i];
boolean b = isValidQuestion(rawQuestion);
if (b){
validQuestions.add(rawQuestion);
}else{
System.out.println("Error: " + rawQuestion + ", input must be a word consist of a-z or A-Z");
}
}

// store valid questions into an array
String questions[] = validQuestions.toArray(new String[validQuestions.size()]);

// shuffle the questions
for(int i=0; i<7; i++){
int x = (int)(Math.random()*validQuestions.size());
int y = (int)(Math.random()*validQuestions.size());
String temp = questions[x];
questions[x] = questions[y];
questions[y] = temp;
}

// game

// initiallize
int noInvalidTry = 0;
int count = 0;
char[] invalidTries = new char[6];
int j = 0;
char[] userGuess = new char[questions[j].length() ];
boolean isCorrect = false;

for(int i=0; i<invalidTries.length; i++){
invalidTries[i] = '_';
}

for(int k=0; k<userGuess.length; k++){
userGuess[k] = '_';
}

这是我搞砸的部分。

        // display banner

while( j<= args.length){
System.out.println( "========" );
System.out.println( "Game: " + ++j );
System.out.println("========");

}

以上

        // game loop

while( noInvalidTry<6 && count<questions[j].length() ){
Scanner sc= new Scanner(System.in);

System.out.print("Please input your guess: ");
String s = sc.nextLine().trim();

// check input length
while(s.length()==1 && isValidQuestion(s)){

//start guess
char inputChar = s.charAt(0);
inputChar = Character.toUpperCase(inputChar);

boolean c = false;
for(int i=0; i<questions[j].length(); i++){
if((s.equals(questions[j].charAt(i))) && (userGuess[i] == '_')){
//update userGuess
userGuess[i] = questions[j].charAt(i);
c = true;
count++;
System.out.println( "Good try!" );
// show status
System.out.printf("No of Invalid try: %d/6\t\tInvalid tries: ",noInvalidTry);
System.out.println( formatCharArray(invalidTries) );

}
}
if(!c){
noInvalidTry++;
System.out.println( "Oops..." );
// show status
System.out.printf("No of Invalid try: %d/6\t\tInvalid tries: ",noInvalidTry);
System.out.println( formatCharArray(invalidTries) );
}
}
}
if( noInvalidTry==6 && count<questions[j].length()){
System.out.println("Game over, the answer is " + questions[j] );
j=j++;
}
if( noInvalidTry<6 && count==questions[j].length()){
System.out.println("Congratulation!");
j=j++;
}
//final status
if(j==args.length){
double temp = 0;
double score = 0;
double total = args.length;
System.out.println("-------------------------------------------------------------------------------------------------------------------");
System.out.println("Summary");
System.out.println("-------------------------------------------------------------------------------------------------------------------");
while(j<=args.length && isCorrect ){
System.out.println(++j + ". " + questions[j] + "\t" + "Correct" + "\t" + count + "/" + questions[j].length() + " Correct guesses" + "\t" + noInvalidTry + "/" + questions[j].length() + " Incorrect guesses" );
temp++;
}
while(j<=args.length && !isCorrect) {
System.out.println(++j + ". " + questions[j] + "\t" + "Incorrect" + "\t" + count + "/" + questions[j].length() + " Correct guesses" + "\t" + noInvalidTry + "/" + questions[j].length() + " Incorrect guesses" );
}
score = temp/total;
System.out.println("Final result: " + score + " / 100 marks");
System.out.println("-------------------------------------------------------------------------------------------------------------------");
}


}
}

最佳答案

    if(j==args.length){

// ...

while(j<=args.length && isCorrect ){
System.out.println(++j + "" + questions[j] + "\t" + "Correct" + "\t" + count + "/" + questions[j].length() + " Correct guesses" + "\t" + noInvalidTry + "/" + questions[j].length() + " Incorrect guesses" );
temp++;
}
while(j<=args.length && !isCorrect) {
System.out.println(++j + ". " + questions[j] + "\t" + "Incorrect" + "\t" + count + "/" + questions[j].length() + " Correct guesses" + "\t" + noInvalidTry + "/" + questions[j].length() + " Incorrect guesses" );
}

如果j是数组长度,那么questions[j]引发错误(最后一个元素是length- 1)

但是,更糟糕的是,您仍在进一步增加 j(2 个 j++ 语句)!

它们还有 while 循环中的许多其他 j++

<小时/>

作为帮助您处理数组的良好实践:当您对作为索引的值进行一些迭代时:

  • 更喜欢 for 循环
  • 循环获取参数的正确值(在 0length-1 之间)
  • 不要不要随机增加数组,您应该确定您的数组索引 (j) 只增加一次且每次只增加一次迭代。为了帮助您做到这一点,您的循环中应该只有一行声明 j++++j,而不是在不同位置嵌套一些 j++在某些 if block 中。
  • (这就是为什么建议使用 for 循环:有一些地方可以执行 j++,并且如果没有 非常好的方法,您不应该在其他地方执行此操作原因。

此外,正如评论中所述,您应该学会分析您的错误( What is a stack trace, and how can I use it to debug my application errors? ),并使用调试工具并逐步检查您的程序,看看您对所有变量做了什么。

关于java - (索引越界)我用java写了一个刽子手游戏程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47511868/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com