如何让我的java代码编译?
这是我的代码,它给出了用户随机方程来测试他们的知识,并且没有出现错误。当我运行代码时,它不会在Eclipse中编译。当我在intelliJ Idea中执行此操作时,它会运行,但没有代码出现,我什么也做不了如何让我的java代码编译?,java,eclipse,intellij-idea,Java,Eclipse,Intellij Idea,这是我的代码,它给出了用户随机方程来测试他们的知识,并且没有出现错误。当我运行代码时,它不会在Eclipse中编译。当我在intelliJ Idea中执行此操作时,它会运行,但没有代码出现,我什么也做不了 package logical; import java.util.Random; import java.util.Scanner; public class logical { @SuppressWarnings("resource") public static void main (
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!");
}
}
您的代码是一个无限循环。
这是真的:
while(again == ("y") || again == ("Y")){
然后,这是while循环中唯一的东西:
for(counter=1;counter>=5;counter++){
立即结束,因为计数器从1开始,您希望它超过5
所以如果你运行这个,while循环将永远循环,什么也不做
将字符串与.equals
或.equalsIgnoreCase
进行比较,而不是与=
进行比较
修复循环的
正确缩进代码
问题在于for循环
for(counter=1;counter>=5;counter++){...}
值计数器=0
已初始化。但是,循环将仅在计数器值为5或大于5后执行,因此不会进入循环。但您在循环中递增“counter”值。因此,输出未打印。代码中的真正罪魁祸首如下:-
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++){
我想提几点:
while循环下的布尔条件永远不会有机会更改
for循环下的计数器变量始终失败
所以执行一直希望在while和for循环之间进行,并陷入了一个永无止境的过程
我希望,这会让你明白。而你的编译错误信息是……?你在这里再次出现逻辑错误==(“y”)
你需要使用equals()
方法比较字符串,而不是使用==
请删除大括号上那些难看的注释。我不在乎你在大学里学过什么,这会让你更难阅读。适当的缩进将完全消除这些注释的需要。我很确定代码是可以编译的,你所拥有的代码并没有按预期工作。没有错误。如果有,请在问题中发布。欢迎使用堆栈溢出。虽然这段代码可以解决这个问题,但如何以及为什么解决这个问题将真正有助于提高您的帖子质量,并可能导致更多的投票。请记住,你是在将来回答读者的问题,而不仅仅是现在提问的人。请编辑您的答案,添加解释,并说明适用的限制和假设。
while(again == ("y") || again == ("Y")){
for(counter=1;counter>=5;counter++){