-4

我正在编写一个小程序,用户必须猜测一个数字。我希望他们输入他们猜测的数字,然后将玩家插入的值分配给变量 x 以检查这是否是正确的值。如何获取插入的值并将其分配给 x 变量?

这是我到目前为止所拥有的:

public static void main(String[] args) {

    Scanner textIn = new Scanner(System.in);
    System.out.println("Try to guess what number I am thinking of.");
    //X is the int I want to change
    int x = 100;

    //Z is the one I am comparing x to
    int z = 10;


    String zGuess = textIn.nextLine();
    boolean xTest = true;
    {
        if (x == z);
        System.out.println("You guessed right!");
    }
    //XTEST PART ONE   
    while (x < z) {
        System.out.println("X < Z");
        break;
    }
    //XTEST PART TWO   
    while (x > z) {
        System.out.println("X > Z");
        break;
    }
}
4

2 回答 2

2

您需要的方法是http://docs.oracle.com/javase/6/docs/api/java/util/Scanner.html#nextInt%28%29

所以在你的情况下,这意味着

你(们)能做到x = textIn.nextInt();

还可以查看 Scanner 的 javadoc http://docs.oracle.com/javase/6/docs/api/java/util/Scanner.html

以及Oracle的教程如何使用Scanner类

http://docs.oracle.com/javase/tutorial/essential/io/scanning.html

于 2013-09-14T23:10:57.597 回答
0

这是一个简单的解决方案。将其包围在一个while循环中并始终设置x = textIn.nextInt()

    public static void main(String[] args) {
    Scanner textIn = new Scanner(System.in);
    System.out.println("Try to guess what number I am thinking of.");
    //X is the int I want to change
    int x = -1;

    //Z is the one I am comparing x to
    int z = 10;

    while(x != z)
    {
        x = textIn.nextInt();
        if(x == z)
        {
            System.out.println("You got it right!");
        }

        else if(x < z)
        {
            System.out.println("Try a higher number.");
        }
        else
        {
            System.out.println("Try a lower number.");
        }

    }
    System.out.println("Great job!")
}
于 2013-09-14T23:23:04.817 回答