循环不会停止,即使设置了限制(计数++)

时间:2016-03-14 00:59:23

标签: loops count

我似乎无法在达到count(5)后停止循环。它只是不断要求。有没有我没看到的东西? 任何帮助是极大的赞赏。         扫描仪键盘=新扫描仪(System.in);         int count = 0;         双回答= 0;         int randomInt1;         int randomInt2;         randomInt1 =(int)(1 + Math.random()* 10 - 1 +1);         randomInt2 =(int)(1 + Math.random()* 10 - 1 +1);

    //System.out.println("Please answer the following problem: ");
    //System.out.println(randomInt1 + "+" + randomInt2 + "=");
    //answer = keyboard.nextDouble();


    count=1;

    while(count < 5)
    {
     System.out.println("Please answer the following problem: ");
    System.out.println(randomInt1 + "+" + randomInt2 + "=");
    answer = keyboard.nextDouble();   

    if(answer != (randomInt1 + randomInt2))
    {
        System.out.println("Sorry, that is not correct.");
         count++;
         break;
    }
    if(answer == (randomInt1 + randomInt2))
    {
        System.out.println("Nice!");
        count++;
        break;
    }


    }
    return answer;
    }

       } 

****修订版

    count=0;
    while(count < 5)
    {
     System.out.println("Please answer the following problem: ");
    System.out.println(randomInt1 + "+" + randomInt2 + "=");
    answer = keyboard.nextDouble();   

     if(answer != (randomInt1 + randomInt2))
    {
     System.out.println("Sorry, that is not correct.");
    }     
     else if(answer == (randomInt1 + randomInt2))
    {
     System.out.println("Nice!");
    }
     count++;
     break;
    }

    return answer;

2 个答案:

答案 0 :(得分:1)

避免在代码上使用break。使用else代替第二个if语句。此外,您应该更好地缩进代码。它有助于阅读。

如果你想数5次,你应该这样做:

count = 0; 
while(count < 5) { 
  ...(your code here)
}

答案 1 :(得分:0)

为什么不在count条件之外增加if

count = 0; 
while(count < 5) { 
  if(condition1){
      // ...
  }
  else{
      // ...
  }
  count++;
}

更新: 以下是完整的代码,可能与您想要的完全相同。

import java.util.Scanner;

class Test {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        int count = 0;
        double answer = 0;
        int randomInt1;
        int randomInt2;
        randomInt1 = (int) (1 + Math.random() * 10 - 1 + 1);
        randomInt2 = (int) (1 + Math.random() * 10 - 1 + 1);
        while (count < 5) {
            System.out.println("Please answer the following problem: ");
            System.out.println(randomInt1 + "+" + randomInt2 + "=");
            answer = keyboard.nextDouble();

            if (answer != (randomInt1 + randomInt2)) {
                System.out.println("Sorry, that is not correct.");
            } else if (answer == (randomInt1 + randomInt2)) {
                System.out.println("Nice!");
                break;
            }
            count++;
        }
    }
}