gpt4 book ai didi

java - 我怎样才能完成这个 stateQuiz.java 程序

转载 作者:行者123 更新时间:2023-12-01 11:35:56 24 4
gpt4 key购买 nike

我想使用数组向用户询问不同状态的问题,但是当我编译它时,它在线程“main”中输出异常。

import java.util.*;

class StateQuiz{

public static void main( String[] args ){
boolean[] asked = new boolean[10];
boolean correct[] = new boolean[10];
Arrays.fill(asked, true);
String [] answers={"Alaska","Ohio","Illinois","Ohio","Florida","Hawaii","New York","California","Maryland","Texas"};
String [] questions={"What is the largest state?","Where is the city of Columbus located?","Where is the city of Springfield located?","Where is Ohio State located?","What is the orange state?","What is the most southern state?","Where is the Big Apple?","Where is Hollywood?","What state is Baltimore located?","What state looks like a boot?"};
int nextQ = -1;
boolean good = false;
do {
nextQ = getNextQuestion(asked);
good = quizUser(answers,questions,nextQ);
asked[nextQ] = true;
if (good == true) {
correct[nextQ] = true;
} else {
correct[nextQ] = false;
}
} while (nextQ != -1);

printResults(correct);
}

public static int getNextQuestion(boolean[] questions_asked){
int[] poo = {};
for (int i = 0; i < questions_asked.length; i ++) {
if (questions_asked[i] == false) {
poo[poo.length] = i;
}
}

if (poo.length == 0) {
return -1;
}

int rand = (int) Math.round(Math.random() * poo.length);
return poo[rand];
}

public static boolean quizUser(String[]answers,String[]questions, int nextQ)
{
System.out.println(questions[nextQ]);
String an;
Scanner keyboard = new Scanner( System.in );
an = keyboard.nextLine();
if(an.equalsIgnoreCase(answers[nextQ])){
System.out.println("Correct");
return true;
}else{
System.out.println("Incorrect");
return false;
}
}


//finding the average correct answers
public static void printResults (boolean[] questions){
int correctQuestions = 0;
double average = 0;
for(int i=0; i < questions.length ; i++) {
if (questions[i]) {
correctQuestions += 1;
}
}

average = correctQuestions / questions.length;

//return average;
System.out.println("Your average socre is:" + average);

if (average > 80) {
System.out.println ("Wow! You really know a lot about state birds!");
} else if (average > 40 && average < 80 ) {
System.out.println ("Apparently you know some state birds.");
} else if (average < 40) {
System.out.println ("You could spruce up your knowledge on state birds.");
}
}
}

最佳答案

问题出在这一行:

int nextQ = -1;

第 15 行将是:

good = quizUser(answers,questions,-1);

并且,代码中的第 48 行将是:

System.out.println(questions[-1]);

因此,您将收到 ArrayIndexOutOfBoundsException,因为您试图访问数组中的第 -1 个元素。

请记住,在 do-while 循环的情况下,它首先执行,然后检查“while”中指定的条件。如果 do-while 让您感到困惑,将其更改为简单的 while 语句可能是最简单的解决方案。

关于java - 我怎样才能完成这个 stateQuiz.java 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29994382/

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