如何修复while循环的运行时错误?

时间:2014-10-02 22:36:28

标签: java while-loop branch

代码在编译器中没有显示错误,但是当代码运行并且循环符合要求时,它会在此处打印出不间断的消息http://i62.tinypic.com/23if4uv.png

这里也是我使用的代码:

Scanner keyb = new Scanner(System.in);
int numbg = (int) (100*Math.random())+1;
String one = "That was lucky!";
String twofour="That was amazing!";
String fivesix= "That was good.";
String seven= "That was okay";
String enine = "That was not versy good";
String tm= "That just insn't your game";
System.out.println("Enter a guess between 1 and 100: ");
int numbu = keyb.nextInt();
int wrong = 0;
while (numbg != numbu) {
    if  (numbu < numbg) {
        System.out.println("Your guess too low. Try again. ");
        wrong++;
        System.out.println("Enter a guess between 1 and 100: ");
        numbu=keyb.nextInt();
    }
    else if (numbu > numbg && numbu <= 100) {
        System.out.println("Your guess too high. Try again.");
        wrong++;
        System.out.println("Enter a guess between 1 and 100: ");
        numbu=keyb.nextInt();
    }
    else if (numbu > 100) {
        System.out.println("Your guess is out of range. Pick a number betwen 1 and 100");
        numbu=keyb.nextInt();
    }
    while (numbg == numbu) {
        if (wrong >= 1) {
            System.out.println(one);
        }
        else if (wrong >= 2 && wrong <= 4) {
            System.out.println(twofour);
        }
        else if (wrong >= 5 && wrong <= 6){
            System.out.println(fivesix);
        }
        else if (wrong == 7) {
            System.out.println(seven);
        }
        else if (wrong >=8 && wrong <= 9){
            System.out.println(enine);
        }
        else if (wrong >= 10) {
            System.out.println(tm);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您拥有的while循环永远不会终止,因为始终满足要求。我建议只使用一个if语句,这样它只会检查一次,如果它符合要求,它只会说一次字符串。此外,您应该更改while循环中应该更改为(错误的&lt; =数字)而不是&gt; =的所有if和if else语句,因为这种情况将始终为真,因为这意味着如果您使用数字OR更多的猜测是找到它而不是那个数字或更少。