我正在写一个小程序,用户必须猜一个数字。我希望他们输入他们正在猜测的数字,然后将玩家插入的值分配给变量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; } }
这是一个简单的解决方案。将其环绕一段时间并始终设置x = textIn.nextInt()
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!") }