这是我正在上课的课程。在编写了大部分程序后,我正在尝试运行它,看起来我有一个逻辑错误。出于某种原因,计算机将执行直到第一个for循环,然后忽略scan.nextInt方法,我尝试提示用户在数组中输入值。
编辑:新问题:现在,当我运行程序时,未正确执行的循环是第二个for循环。无论您输入什么,它都会返回正确的总数。也返回0%正确:(
编辑2:我修正了百分比正确部分的问题,但我仍然无法正确地比较评分测验时输入的正确答案的输入值。 ..它始终将正确的数字返回为问题的总数,无论它们是否正确。
import java.util.Scanner;
public class gradingQuizzes {
public static void main(String[] args)
{
int numQuestions; // number of questions on quiz
int numCorrect = 0; // number correct of entered values
int correctAnswer;
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the amount of questions in the Quiz: ");
numQuestions = scan.nextInt();
int[] key = new int[numQuestions]; // creates an array for the key to the quiz
// Prompts the user to enter values into the key array
for (int i = 0; i < key.length; i++)
{
System.out.println("Please enter the correct answer to question number " + (i + 1) + " : ");
key[i] = scan.nextInt();
}
System.out.println("Please enter the answers for the quiz to be graded: ");
System.out.println("---------------------------------------------------");
// 'for' loop asking for the correct answer for each question on the quiz
for (int i = 0; i < key.length; i++)
{
System.out.println("Question " + (i + 1) + " answer: ");
correctAnswer = scan.nextInt();
if (correctAnswer == key [i]);
{
numCorrect++; // increments the number correct for each match to the key
}
}
// Creates a variable to compute the percent correct on the quiz
double percentCorrect = (numCorrect / (key.length));
System.out.println("The number correct is: " + numCorrect);
System.out.println("The percent correct: %" + percentCorrect);
}
答案 0 :(得分:2)
您正在使用0大小初始化数组(请注意,您使用0初始化numQuestions
)。在获取用户输入的numQuestions
值后,只需移动数组初始化:
numQuestions = scan.nextInt();
int[] key = new int[numQuestions];
如果您想使用double
/ int
将long
值分配给double
变量,则应投标int
/ long
至double
或将其乘以1.0
(字面值),否则浮点结果将为int
/ long
。修改这部分代码:
double percentCorrect = ((numCorrect * 1.0) / ((key.length + 1) * 1.0) );
如果要将格式化文本打印到输出,则应使用System.out.printf
。我将写一个最终代码的例子(关于语言语法):
//System.out.println("The percent correct: %" + percentCorrect);
System.out.printf("The percent correct: %% %.2f\n", percentCorrect);
从上面的链接:
%%
将打印%
符号%.2f
将使用2个固定小数\n
将打印换行符答案 1 :(得分:0)
这是因为您正在使用key.length
。数组没有任何元素,因此返回0。
答案 2 :(得分:0)
您已宣布
int[] key = new int[numQuestions];
当numQuestions为0时
这将有效
numQuestions = scan.nextInt();
key = new int[numQuestions];
对于问题的第二部分,if语句的末尾有一个分号。 删除它
if (correctAnswer == key [i]);
答案 3 :(得分:0)
int numQuestions = 0; // number of questions on quiz
int numCorrect = 0; // number correct of entered values
int correctAnswer;
int[] key = new int[numQuestions];
这里numQuestions被声明为0.更改为有效。