-3

我有这个程序可以生成一个你必须猜测的随机数。如果它太高或太低,它会告诉你。我需要在每次猜测后询问您是否要继续。我尝试使用嵌套的 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: ");
  }


      }
   }    
}
4

1 回答 1

1

您可以尝试在 while 循环检查中添加新的布尔值。

while (win == false && shouldContinue == true)

然后问问题,

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.");
      } 

顺便说一句,如果这不起作用,请包括您给出错误的代码。

于 2013-11-03T03:00:21.640 回答