错过'你的号码是对的'句子

时间:2014-12-06 22:11:34

标签: java

我编写了一个简单的随机数生成器,您需要猜测它是什么数字,但由于某些原因,如果您输入的数字是正确的,它将无法打印出来。有人可以看一下吗? 我在java btw中的菜鸟...自学...

package randomnumbergenerator;
import java.util.Random;
import java.util.Scanner;

public class main {
    public static void main(String args[])
    {
        System.out.println("Enter the lowest border");
        Scanner scannerx = new Scanner(System.in);
        int y = scannerx.nextInt();
        System.out.println("Enter the highest border");
        Scanner scannery = new Scanner(System.in);
        int x = scannery.nextInt();
        Random random = new Random();
        int randomnummer = random.nextInt(x) + y;
        System.out.println("Now try to guess the number!");
        Scanner guessingnumber = new Scanner(System.in);
        int guessednumber = guessingnumber.nextInt();
        while(randomnummer != guessednumber){   
            if (randomnummer == guessednumber){
            System.out.println("you guessed it right!");
            }
            if(randomnummer >= guessednumber){
            System.out.println("the number you guessed it wrong, its higher!");
            }
            if(randomnummer <= guessednumber){
            System.out.println("the number you guessed it wrong, its lower!");
            }
            System.out.println("try again!");
            Scanner guessingnumber1 = new Scanner(System.in);
            guessednumber = guessingnumber1.nextInt();
        }
    }

} 提前谢谢!

2 个答案:

答案 0 :(得分:6)

您的第if (randomnummer == guessednumber){行位于while(randomnummer != guessednumber)的while循环中。这两个条件不可能都是真的,因此永远不会满足if条件。

您可以在while循环结束后移动“您猜对了”消息。

答案 1 :(得分:0)

试试这个

while(randomnummer != guessednumber){   

   if(randomnummer > guessednumber){
       System.out.println("the number you guessed it wrong, its higher!");
   } else {
       System.out.println("the number you guessed it wrong, its lower!");
   }
   System.out.println("try again!");
   Scanner guessingnumber1 = new Scanner(System.in);
   guessednumber = guessingnumber1.nextInt();
}

System.out.println("you guessed it right!");