基于用户输入的Java循环

时间:2013-11-03 02:52:54

标签: java loops jgrasp

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

  }
  } 
}

EDITED

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


      }
   }    
}

1 个答案:

答案 0 :(得分: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.");
      } 

顺便说一下,如果这不起作用,请包含出错的代码。