如何编译我的java代码?

时间:2016-08-22 10:36:21

标签: 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 (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!");
}
}

4 个答案:

答案 0 :(得分:0)

你的代码是一个无限循环 这开始是真的:

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

然后这是while循环中唯一的东西:

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

立即结束,因为counter从1开始,你预计它会超过5。

因此,如果你运行它,while循环将永远循环,什么都不做。

  1. 将字符串与.equals.equalsIgnoreCase进行比较,而不是==

  2. 修复您的for循环。

  3. 正确缩进代码。

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

我想提几点:

  1. while循环下的布尔条件永远不会有机会改变。
  2. for循环下的计数器变量总是失败。
  3. 因此,执行一直希望在while和for循环之间,并且陷入永无止境的过程。
  4. 我希望,这将表明清楚。

答案 3 :(得分:0)

while(again == ("y") || again == ("Y")){
for(counter=1;counter>=5;counter++){