我有这个程序可以生成一个你必须猜测的随机数。如果它太高或太低,它会告诉你。我需要在每次猜测后询问您是否要继续。我尝试使用嵌套的 if 语句并不断收到各种错误。我正在使用 jgrasp 对此进行编码。顺便说一句,我是编码新手。
import java.util.*;
import java.text.*;
public class redo
{
public static void main(String [] args)
{
//Generate a random number and set values
Random r = new Random();
int number = r.nextInt(100);
System.out.println(number);
boolean win = false;
//Loop
while (win == false)
{
//Input guess
System.out.println("Please guess a number 1-100:");
Scanner scan = new Scanner(System.in);
int guess = scan.nextInt();
//Compare input with correct answer
if (guess == number)
{
System.out.println("You are correct! the number was " + number + "!");
win = true;
}
else if (guess > number)
{
System.out.println("That number is too high.");
}
else if (guess < number)
{
System.out.println("That number is too low.");
}
}
}
}
已编辑
import java.util.*;
import java.text.*;
public class redo
{
public static void main(String [] args)
{
//Generate a random number and set values
Random r = new Random();
int number = r.nextInt(100);
System.out.println(number);
boolean win = false;
//Loop
while (win == false)
{
//Input guess
System.out.println("Please guess a number 1-100:");
Scanner scan = new Scanner(System.in);
int guess = scan.nextInt();
//Compare input with correct answer
if (guess == number)
{
System.out.println("You are correct! the number was " + number + "!");
win = true;
}
else if (guess > number)
{
System.out.println("That number is too high.");
}
else if (guess < number)
{
System.out.println("That number is too low.");
}
System.out.println("Would you like to guess again? Please enter Y or N: ");
String yesorno = scan.next();
char nooryes = yesorno.charAt(0);
char No = 'N';
char no = 'n';
char Yes = 'Y';
char yes = 'y';
while (win == true)
if (nooryes == No || nooryes == no)
{
win = true;
}
else if (nooryes == Yes || nooryes == yes)
{
win = false;
}
else
{
System.out.println("I can't read that. Please enter Y or N: ");
}
}
}
}