[英]Capital/State Guessing Game 2D Arrays
我一直在網上尋找,發現有一些人能夠完成這種代碼,但沒有人為我直接看到的問題提供解決方案。 此處的任務是讓程序詢問用戶“亞利桑那州的首都是什么”。 用戶需要輸入諸如Phoenix之類的大寫字母,它會獎勵一個分數並一直移至下一個問題,同時計算正確答案的數量,並在完成后將其顯示在輸出的底部。 運行我的程序時,它詢問列表中第一個狀態的首字母。 一旦完成,它將提供一個要點,但隨后吐出其余狀態,說它們是正確的,但不會使用戶有機會進入下一個狀態。 好像我錯過了當第一個州被回答時會回到原始問題“輸入所列州的首都”的部分一樣。有人可以提供幫助嗎? 我相信我需要一個類似if,if,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;
}
}
您必須將問題和輸入移動到for循環內,您只要求輸入一次,如果正確,則它將打印所有正確的內容,或者以其他方式輸出。 下面的兩行應位於for循環內。
System.out.println("Enter the Capital of the State listed: " + capitals[i][0]);
userInput = scnr.next();
我認為有50個州(不是49個州)? 另外,如果更改為50,則條件應為< NUMBER_OF_STATES
而不是<=,否則您將擁有ArrayIndexOutOfBounds。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.