一尘不染

我如何更改int值?

java

我正在写一个小程序,用户必须猜一个数字。我希望他们输入他们正在猜测的数字,然后将玩家插入的值分配给变量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;
    }
}

阅读 228

收藏
2020-12-03

共1个答案

一尘不染

这是一个简单的解决方案。将其环绕一段时间并始终设置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!")
}
2020-12-03