如何让我的java代码编译?

问题描述:

这是我的代码,它给用户随机方程来测试他们的知识,并且没有错误出现。当我运行代码时,它只是不能在Eclipse中编译。当我执行intelliJ Idea时,它会运行,但没有代码出现,我什么也做不了。如何让我的java代码编译?

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!"); 
} 
} 
+8

和您的编译错误消息是.....? –

+0

这里你有逻辑错误'again ==(“y”)'你需要使用'equals()'方法比较字符串,而不是'==' –

+3

请删除花括号上那些丑陋的评论。我不在乎你在大学教过什么,这使得阅读更难。 – byxor

您的代码是一个无限循环。
这开始为真:

while(again == ("y") || again == ("Y")){ 

然后这一点,这是while循环里面的唯一的事情:

for(counter=1;counter>=5;counter++){ 

立即结束,因为counter从1开始,且将其期待超过5.

所以如果你运行这个,while循环将永远循环,无所事事。

  1. 比较字符串与.equals.equalsIgnoreCase,不==

  2. 修复您的for循环。

  3. 正确缩进您的代码。

问题是与for循环

for(counter=1;counter>=5;counter++){...} 

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++){ 

几点我想提一下:

  1. 布尔条件下while循环从来没有得到机会来改变。
  2. for循环下的计数器变量总是失败。
  3. 因此,执行期间继续希望while和for循环,并陷入永无止境的过程。

我希望这会说清楚。