编写一个Java程序,生成五个问题,并在学生回答所有五个问题后报告正确答案的数量
我是java新手,我正在尝试编写一个代码来显示他们答对的问题的数量,而不是他们每个问题都答对了。当我试着运行它时,我不能让它显示他们答对的问题的数量。例如,我想让它说“你5个问题中有4个是正确的!”,这取决于他们答对了多少。这就是我到目前为止所做的:编写一个Java程序,生成五个问题,并在学生回答所有五个问题后报告正确答案的数量,java,Java,我是java新手,我正在尝试编写一个代码来显示他们答对的问题的数量,而不是他们每个问题都答对了。当我试着运行它时,我不能让它显示他们答对的问题的数量。例如,我想让它说“你5个问题中有4个是正确的!”,这取决于他们答对了多少。这就是我到目前为止所做的: import java.util.Scanner; public class Addition { public static void main(String[] args) { Scanner sc = new Scann
import java.util.Scanner;
public class Addition {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int count = 0;
while (count < 5){
int number1 = (int)(Math.random() * 100);
int number2 = (int)(Math.random() * 100);
System.out.println("What is " + number1 + " + " + number2 + "?");
count++;
int answer = number1 + number2;
int guess = sc.nextInt();
boolean correct = guess == answer;
if (guess == answer){
}
System.out.println("You got " + correct + " correct");
}
}
}
import java.util.Scanner;
公共类添加{
公共静态void main(字符串[]args){
扫描仪sc=新的扫描仪(System.in);
整数计数=0;
同时(计数<5){
int number1=(int)(Math.random()*100);
int number2=(int)(Math.random()*100);
System.out.println(“什么是“+number1+”+“+number2+”?”);
计数++;
int answer=数字1+数字2;
int guess=sc.nextInt();
布尔正确=猜测==答案;
如果(猜测=答案){
}
System.out.println(“您得到了”+正确+“正确”);
}
}
}
您的逻辑需要稍作更改
int correctAnswer = 0; // this is a new variable you have to introduce before while (count < 5){
if (guess == answer){
correctAnswer++;
}
// This line should be outside of while loop as well..
System.out.println("You got " + correctAnswer + " out of " + count + " questions correct");
int correctAnswer=0;//这是一个新变量,您必须在while之前引入(count<5){
如果(猜测=答案){
正确答案++;
}
//这条线也应该在while循环之外。。
System.out.println(“你得到了”+correctAnswer+“出”+count+“问题正确”);
您的代码中有两个问题:
(1) 没有正确答案的计数;
(2) 完成后不要打印。
测试正在进行时,您确实有一个打印,但这不是您说要打印的时候。请尝试以下两个更改:在if语句中计数和在循环后打印
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int count = 0;
while (count < 5){
...
boolean correct = guess == answer;
if (guess == answer){
correct++;
}
}
System.out.println("You got " + correct + " out of " + count " questions correct");
}
publicstaticvoidmain(字符串[]args){
扫描仪sc=新的扫描仪(System.in);
整数计数=0;
同时(计数<5){
...
布尔正确=猜测==答案;
如果(猜测=答案){
正确的++;
}
}
System.out.println(“你得到了“+correct+”中的“+count”问题正确”);
}