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