一旦最后一个问题得到解答,该程序应该结束并给出正确答案的数量。相反,程序回到循环中的初始问题。 “阿拉巴马州的首都是什么”
package exercise09_17;
import java.util.Scanner;
public class exercise09_17 {
static Scanner input = new Scanner(System.in).useDelimiter("\r\n");
public static void main(String[] args) {
int correctAnswer = 0;
String [][] grid = {
{"Alabama", "California", "Delaware", "Florida", "Georgia",
"Hawaii", "Idaho", "Kansas", "Lousiana", "Maryland", "New Mexico", "Oregon",
"Pennsylvania", "Rhode Island", "South Carolina", "Texas", "Utah", "Virgina",
"West Virginia"},
{"Montgomery", "Sacramento", "Dover", "Tallahassee", "Atlanta",
"Honolulu", "Boise", "Topeka", "Baton Rouge", "Annapolis", "San Jose", "Salem",
"Harrisburg", "Providence", "Columbia", "Austin", "Salt Lake City", "Richmond",
"Charleston"}};
for(int i = 0; i< grid.length; i++){
for(int k = 0; k < grid[i].length; k++ ){
System.out.println("What is the capital of " + grid[0][k] + "?");
String capital = input.next();
String answer = grid[1][k];
if(capital.equalsIgnoreCase(answer)){
correctAnswer ++;
System.out.println("Your answer is correct");
}
else
System.out.println("The correct answer should be " + answer);
}
}
System.out.println("The correct count is " + correctAnswer);
}
}
答案 0 :(得分:1)
这不是无限的。它只是两次:
for(int i = 0; i< grid.length; i++){
此处不需要此i
变量,因此也不需要整个外循环,因为您在第一次使用时同时使用两个子阵列grid[0]
和grid[1]
通过
答案 1 :(得分:1)
尝试删除无关的for loop
:
public class exercise09_17 {
static Scanner input = new Scanner(System.in).useDelimiter("\r\n");
public static void main(String[] args) {
int correctAnswer = 0;
String [][] grid = {
{"Alabama", "California", "Delaware", "Florida", "Georgia",
"Hawaii", "Idaho", "Kansas", "Lousiana", "Maryland", "New Mexico", "Oregon",
"Pennsylvania", "Rhode Island", "South Carolina", "Texas", "Utah", "Virgina",
"West Virginia"},
{"Montgomery", "Sacramento", "Dover", "Tallahassee", "Atlanta",
"Honolulu", "Boise", "Topeka", "Baton Rouge", "Annapolis", "San Jose", "Salem",
"Harrisburg", "Providence", "Columbia", "Austin", "Salt Lake City", "Richmond",
"Charleston"}};
for(int k = 0; k < grid[0].length; k++ ){
System.out.println("What is the capital of " + grid[0][k] + "?");
String capital = input.next();
String answer = grid[1][k];
if(capital.equalsIgnoreCase(answer)){
correctAnswer ++;
System.out.println("Your answer is correct");
} else
System.out.println("The correct answer should be " + answer);
}
System.out.println("The correct count is " + correctAnswer);
}
}
答案 2 :(得分:0)
更改
System.out.println("What is the capital of " + grid[0][k] + "?");
到
System.out.println("What is the capital of " + grid[i][k] + "?");
由于您在完成所有k次迭代后使用grid[0][k]
,因此会在同一i=0
上再次进行另一次k迭代,直到i<grid.length
答案 3 :(得分:0)
您没有无限循环,但您将重复该过程的次数与网格长度一样多。基本上,您不需要外部for循环。删除循环
for(int i = 0; i < grid.length; i++)
而不是
for(int k = 0; k < grid[i].length; k++ ){
更改为
for(int k = 0; k < grid[0].length; k++ ){