我一直在网上寻找并找到了一些能够完成这类代码的人,但没有为我直接看到的问题提供解决方案。这里的任务是让程序询问用户“亚利桑那州的首都是什么”。用户需要输入凤凰之类的资本,它将奖励一个点并移动到下一个问题,同时计算正确答案的数量并在完成时在输出的底部显示它们。在运行我的程序时,它会询问列表中第一个州的首都。一旦完成它将提供一个点,但然后吐出其他州说他们是正确的但不给使用机会进入下一个状态。就好像我错过了一个部分,当第一个状态得到回答时,它将回到原来的“输入所列州的首都”的问题。有人可以协助吗?我相信我需要一个声明,如if,else if和else但是看不出我将如何在这里应用它或者我应该尝试另一个循环。我无法让do循环正常工作。有什么建议?我的代码如下。
import java.util.Scanner;
public class StatesArray {
static Scanner scnr = new Scanner(System.in);
public static void main(String[] args) {
int correctStates = 0;
String userInput = "";
int i = 0;
final int NUMBER_OF_US_STATES = 49;
String capitals [][] = {
{"Alabama", "Montgomery"},
{"Alaska", "Juneau"},
{"Arizona", "Phoenix"},
{"Arkansas", "Little Rock"},
{"California", "Sacramento"},
{"Colorado", "Denver"},
{"Connecticut", "Hartford"},
{"Delaware", "Dover"},
{"Florida", "Tallahasse"},
{"Georgia", "Atlanta"},
{"Hawaii", "Honolulu"},
{"Idaho", "Boise"},
{"Illinois", "Springfield"},
{"Indiana", "Indianapolis"},
{"Iowa", "Des Moines"},
{"Kansas", "Topeka"},
{"Kentucky", "Frankfort"},
{"Louisiana", "Baton Rouge"},
{"Maine", "Augusta"},
{"Maryland", "Annapolis"},
{"Massachusettes", "Boston"},
{"Michigan", "Lansing"},
{"Minnesota", "Saint Paul"},
{"Mississippi", "Jackson"},
{"Missouri", "Jefferson City"},
{"Montana", "Helena"},
{"Nebraska", "Lincoln"},
{"Nevada", "Carson City"},
{"New Hampshire", "Concord"},
{"New Jersey", "Trenton"},
{"New York", "Albany"},
{"New Mexico", "Santa Fe"},
{"North Carolina", "Raleigh"},
{"North Dakota", "Bismark"},
{"Ohio", "Columbus"},
{"Oklahoma", "Oklahoma City"},
{"Oregon", "Salem"},
{"Pennslyvania", "Harrisburg"},
{"Rhode Island", "Providence"},
{"South Carolina", "Columbia"},
{"South Dakota", "Pierre"},
{"Tennessee", "Nashville"},
{"Texas", "Austin"},
{"Utah", "Salt Lake City"},
{"Vermont", "Montpelier"},
{"Virginia", "Richmond"},
{"Washington", "Olympia"},
{"West Virginia", "Charleston"},
{"Wisconsin", "Madison"},
{"Wyoming", "Cheyenne"}
};
System.out.println("Enter the Capital of the State listed: " + capitals[i][0]);
userInput = scnr.next();
i = 0;
for(i = 0; i <= NUMBER_OF_US_STATES; i++){
if(capitals[i][1].equals(userInput)) {
correctStates++;
System.out.println("Yes that is the capital of " + capitals[i][0] + ".");
}
else {
System.out.println("No that is not the capital of " + capitals[i][0] + ".");
i++;
}
}
//counts the number of correct guesses.
System.out.println("Total number of capitals answered correctly: " + correctStates + ".");
i++;
return;
}
}
答案 0 :(得分:0)
你必须在for循环中移动问题和输入,你只需要输入一次,如果这是正确的,那么它将打印所有正确的,或者另一种方式。下面的两行应该在for循环中。
System.out.println("Enter the Capital of the State listed: " + capitals[i][0]);
userInput = scnr.next();
我认为有50个州(不是49个)?此外,如果您更改为50,则您的条件应为< NUMBER_OF_STATES
而不是&lt; =,否则您将拥有ArrayIndexOutOfBounds。