我做了一个非常简单的猜谜游戏。但我想计算用户在找到原始号码之前所做的尝试总数。这意味着一旦隐藏号码与用户输入相匹配,它就应该告诉用户赢得了多少号码。
这是我的代码:
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");
}
}
}
}
答案 0 :(得分:1)
银行足球比赛 } else if(guessedNum&lt; hiddenNum){ System.out.println(“不匹配!尝试更大的数字”);
//checking another condition
} else if (guessedNum > hiddenNum) {
System.out.println("Not matched! Try a smaller number");
}
}
}
}
答案 1 :(得分:0)
试试这个:
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");
}
}
}
答案 2 :(得分:0)
这个回复更适合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
那里。