我做了一个非常简单的猜谜游戏。但我想计算用户在找到原始数字之前所做的尝试总和。这意味着一旦隐藏数字与用户输入匹配,它应该告诉用户在获胜之前输入了多少数字。
这是我的代码:
package guessinggame;
import java.util.Scanner;
public class GuessingGame {
public static void main(String[] args) {
int hiddenNum = 10;
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("Enter a numebr by guessing: ");
int guessedNum = input.nextInt();
if (guessedNum == hiddenNum) {
System.out.println("Congratulation! Your number is matched");
System.exit(0);
} else if (guessedNum < hiddenNum) {
System.out.println("Not matched! Try a bigger number");
} else if (guessedNum > hiddenNum) {
System.out.println("Not matched! Try a smaller number");
}
}
}
}
版本 } else if (猜测数 < hiddenNum) { System.out.println("Not matched! Try a bigger number");
//checking another condition
} else if (guessedNum > hiddenNum) {
System.out.println("Not matched! Try a smaller number");
}
}
}
}
试试这个:
public static void main(String[] args) {
//storing the hidden number in a variable
int hiddenNum = 10;
//introducing the scanner class (for user input)
Scanner input = new Scanner(System.in);
//asking user to enter a random number
int attempts = 0; // use as a counter
while (true) {
System.out.println("Enter a numebr by guessing: ");
//Storing that into a variable
int guessedNum = input.nextInt();
attempts += 1;
//Checking wheather the number is matched
if (guessedNum == hiddenNum) {
System.out.println("Congratulation! Your number is matched");
//System.out.println("You have made total of " + attempts +" attempts to find the number!");
//If matched number found, terminate the program
System.exit(0);
//checking another condition
} else if (guessedNum < hiddenNum) {
System.out.println("Not matched! Try a bigger number");
//checking another condition
} else if (guessedNum > hiddenNum) {
System.out.println("Not matched! Try a smaller number");
}
}
}
此回复更适合在 http://codereview.stackexchange.com 但就在这里。
package guessinggame;
import java.util.Scanner;
public class GuessingGame {
public static void main(String[] args) {
int hiddenNum = 10;
int guessedNum = 0;
Scanner input = new Scanner(System.in);
boolean running = true;
for (int i = 1; running; i++) {
System.out.println("Enter a number to guess: ");
guessedNum = input.nextInt();
if (guessedNum == hiddenNum) {
System.out.println("Congratulation! Your number is matched");
System.out.println("You have made " + i + " to find the number!");
running = false;
} else if (guessedNum < hiddenNum) {
System.out.println("Not matched! Try a bigger number");
} else {
System.out.println("Not matched! Try a smaller number");
}
}
}
}
代码的一些更改:
while (true)
和“随机”终止程序。相反,我引入了 boolean
变量。它可以保存 true
或 false
的值。我一开始就把它设置为 true
,然后如果用户猜对了,就把它设置为 false
。while
循环是更好的练习,我只是想展示一个for
循环。)else
在那里。 mlk.,m jnhb41564104165416546544165416541562184512465845124651284512987451284512