这是我的代码,它为用户提供随机方程式来测试他们的知识,并且没有出现任何错误。当我运行代码时,它只是不在Eclipse中编译。当我在intelliJ Idea中运行时,它会运行但没有代码出现,我无法做任何事情。
package logical;
import java.util.Random;
import java.util.Scanner;
public class logical {
@SuppressWarnings("resource")
public static void main (String args[]){
int qn1, qn2; //Numbers for the question
int ua; //The users answer
int answer; //The actual answer
int counter = 0; //Controls the number of questions that can be answered
int tally = 0; //Number of correct responses
String again = "y";
Scanner in = new Scanner(System.in);
Random dice = new Random();
while(again == ("y") || again == ("Y")){
for(counter=1;counter>=5;counter++){
qn1 = 1+dice.nextInt(40);
qn2 = 1+dice.nextInt(40);
answer = qn1 + qn2;
System.out.printf("What is %d + %d",qn1,qn2);
ua = in.nextInt();
if(ua == answer){
System.out.println("That is correct!");
counter++;
tally++;
}
else{
System.out.println("Sorry, that is wrong! The correct answer is " + answer);
}
System.out.println("Would you like to try again?(Y/N)");
again = in.next();
if(again=="y" || again=="Y"){
counter=0;
}else {
System.out.println("Thanks for playing your results were " + tally + " out of 5");
}
}
}
System.out.println("Thanks for taking the math challenge!");
}
}
答案 0 :(得分:0)
你的代码是一个无限循环 这开始是真的:
while(again == ("y") || again == ("Y")){
然后这是while循环中唯一的东西:
for(counter=1;counter>=5;counter++){
立即结束,因为counter
从1开始,你预计它会超过5。
因此,如果你运行它,while循环将永远循环,什么都不做。
将字符串与.equals
或.equalsIgnoreCase
进行比较,而不是==
。
修复您的for
循环。
正确缩进代码。
答案 1 :(得分:0)
问题在于for循环
for(counter=1;counter>=5;counter++){...}
初始化值counter=0
。但是,只有在计数器值为5或大于5之后才会执行循环,因此不会进入循环。但是你在循环内增加了“计数器”值。因此,输出没有打印。
答案 2 :(得分:0)
代码中真正的罪魁祸首如下: -
String again = "y";
////////DECLARATION///////////////
Scanner in = new Scanner(System.in);
Random dice = new Random();
////////NOW THE MAGIC HAPPENS/////
while(again == ("y") || again == ("Y")){
for(counter=1;counter>=5;counter++){
我想提几点:
我希望,这将表明清楚。
答案 3 :(得分:0)
while(again == ("y") || again == ("Y")){
for(counter=1;counter>=5;counter++){