编写程序以生成1到100之间的随机数并将其保留为密码。然后程序将检查用户是否可以猜出密码。用户可以继续猜测号码,直到找到号码或用户可以输入0,这将终止该程序。
每次用户猜测时,程序都会报告如下:
如果密码为74且用户输入26,程序将打印“Way too Low”。如果用户然后说65,那么程序将打印“A Little Low
我对if语句感到困惑,也许我的结构不正确。我不确定。
import java.util.Scanner;
public class SecretNumber {
public static void main(String[] args){
int random1, answer;
Scanner input = new Scanner(System.in);
random1 = (int)(Math.random()*10);
System.out.print(random1);
System.out.println("Guess the number");
answer = input.nextInt();
while(answer != 0) {
if (answer > (random1 + 30)){
System.out.println("Way to high");
}
else if ( answer > ( random1 - 30)){
System.out.println("Way to low");
}
else if (answer > random1 + 10 && answer < random1 + 30){
System.out.println("High");
}
else if (answer > random1 - 10 && answer < random1 - 30 ){
System.out.println("Low");
}
else if ( answer > random1 + 10){
System.out.println("A little high");
}
else if ( answer < random1 - 10){
System.out.println("A little low");
}
else if ( answer == random1){
System.out.println("That is correct");
System.exit(0);
}
else {
System.out.println("Guess the number");
answer = input.nextInt();
}
}
}
}
答案 0 :(得分:2)
将从最终的else块输入的行移到else的旁边(但仍在循环中),它将正常工作。
你想要这样做的原因是因为它再次进入猜测条件之一(例如,“方式太低!”)然后从不进入最后的其他条件,从而导致无限循环。
while (answer !=0){
// ommitted
else if ( answer == random1){
System.out.println("That is correct");
System.exit(0);
}
System.out.println("Guess the number");
answer = input.nextInt();
}
答案 1 :(得分:0)
我改变了一点并以某种方式格式化我感觉更好然而你可以根据自己的喜好复制和粘贴并重新格式化,我也删除了关闭的方法并将其改为低于或高于但你可以添加如果你愿意,那就回来了
/*
*/
package randomnumbergame;
import java.util.Scanner;
public class Randomnumbergame
{
public static void main(String[] args)
{
int random1, answer;
Scanner input = new Scanner(System.in);
random1 = (int)(Math.random()*100);
System.out.println("Guess the number I am thinking of, it is between 1 and a 100 or press 0 to quite");
answer = input.nextInt();
while(answer != 0)
{
if (answer > random1)
{
System.out.println("Your guess is to high");
}
else if ( answer > random1)
{
System.out.println("Your guess is to low");
}
else
{
System.out.println("That is correct");
}
System.out.println("Guess the number I am thinking of, it is between 1 and a 100 or press 0 to quite");
answer = input.nextInt();
}
}
}
另一方面,该程序正在为我工作,但不管我似乎猜测它通常似乎告诉我我是正确的= /,我知道math.random部分是正确的,因为这是我用于今天上课,这也是我的导师告诉我使用的。