gpt4 book ai didi

java - 为什么我的计数器没有计数,并且我的 ArrayList 没有将新的整数值添加到数组中?

转载 作者:行者123 更新时间:2023-12-01 17:34:12 28 4
gpt4 key购买 nike

我的问题的主要来源来 self 的方法“add”和数组“mathAnswers”以及计数器“score”。

我正在尝试比较数组值,使它们执行数学函数,然后检查用户输入是否与答案匹配。我还希望将正确的答案添加到数组中,然后打印出该数组以及验证用户分数的计数器。

我遇到了一个问题,我的计数器没有递增,我的值没有输入到我的数组中,并且所有内容都保持为 0。这是我的代码。

    import java.util.Scanner;
import java.util.ArrayList;
public class Program7 {

public static void main(String[] args) {
int [] mathQuizLeft = {
8, //0
14, //1
16, //2
8, //3
17, //4
5, //5
27, //6
4, //7
20, //8
13, //9
};

int [] mathQuizRight = {
13, //0
12, //1
4, //2
18, //3
4, //4
4, //5
9, //6
7, //7
4, //8
4, //9
};


Scanner scanner = new Scanner(System.in);

double userAns = 0;
double answer = 6;

System.out.println("Welcome to the 3rd Grade Math Quiz. \n");
System.out.println("The Quiz begins now: \n"
+ "1. 8 - 13\n2. 14 + 12\n3. 16 / 4\n4. 8 + 18\n5. 17 % 4\n6. 5 x 4\n"
+ "7. 27 / 9\n8. 4 - 7\n9. 20 x 4\n10. 13 - 4");

for(int i = 0; i <= 10; i++) {
if (i < 10) {
System.out.printf("%d. ", (i + 1));
userAns = Double.valueOf(scanner.nextDouble());
add(mathQuizLeft, mathQuizRight, i, answer, userAns);
}
else {
add(mathQuizLeft, mathQuizRight, i, answer, userAns);
}
}
}



public static void add(int[] array1, int[] array2, int i, double answer, double userAns) {
ArrayList<Integer> mathAnswers = new ArrayList<>(); //for storing functions

int score = 0;

if (i == 1 || i == 3) { //addition
answer = array1[i] + array2[i];
if (userAns == answer) {
score++;
mathAnswers.add(i);
}
} else if (i == 0 || i == 7 || i == 9) { //subtraction
answer = array1[i] - array2[i];
if (userAns == answer) {
score++;
mathAnswers.add(i);
}
} else if (i == 5 || i == 8) { //multiplication
answer = array1[i] - array2[i];
if (userAns == answer) {
score++;
mathAnswers.add(i);
}
} else if (i == 2 || i == 6) { //multiplication
answer = array1[i] - array2[i];
if (userAns == answer) {
score++;
mathAnswers.add(i);
}
} else if (i == 4) { //multiplication
answer = array1[i] - array2[i];
if (userAns == answer) {
score++;
mathAnswers.add(i);
}
} else if (i == 10) {
for (double array: mathAnswers) {
System.out.println(array);
}
System.out.println(score);
}
}
}

最佳答案

您的错误在于 add() 方法。您在每个正确答案后计算分数并将 i 添加到 ArrayList,但您并没有保护 arraylist 和分数。您必须将 ArrayList 和分数声明为全局,或者必须返回它并将其保存在 main() 方法中。

public class Program7 {
private static int score = 0;
private static ArrayList<Integer> mathAnswers = new ArrayList<>();

public static void main(String[] args) {
...
}

public static void add(...) {
if(...) {
...
}
...
}
}

关于java - 为什么我的计数器没有计数,并且我的 ArrayList 没有将新的整数值添加到数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61070525/

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