有重新运行程序的问题

时间:2016-02-23 03:00:21

标签: java loops

我正在编写一个程序,要求用户猜测一个随机数6次。该计划必须询问他们是否想要再次参加比赛,并且将保持赢/输的总计。 如何重新运行该程序?

继承人代码:

    import java.util.Scanner;
import java.util.Random;

public class Project {
  public static void main(String[] args) {

String input;
double guess = 0;
int number;
double wins = 0;
double losses = 0;
String repeat;

Scanner keyboard = new Scanner(System.in);
  Random randomNumbers = new Random();

System.out.println("Welcome to Higher/Lower!");

System.out.println("Enter your name: ");
input = keyboard.nextLine();

while(input.equalsIgnoreCase("yes")); {
  number = randomNumbers.nextInt(100) + 1;
  System.out.println("I've chosen my number, " + input + "You only have 6 tries, good luck!"); }

  for(int num = 1; number != guess && number <= 6; num++) {
    System.out.println("Enter guess " + num + ":");
    guess = keyboard.nextDouble();
    if(guess < number)
      System.out.println("higher.");
    else if(guess > number)
      System.out.println("lower.");
    else
      System.out.println("Congratulations!"); }

                           if(guess == number)    {
      System.out.println("You guesses my number!"); wins++; }
                           if(guess != number) {
                           System.out.println("Sorry, " + input + " my number was " + number +
                                              "You lose!"); losses++; }

                         System.out.println("Do you want to play again? (Yes/No): ");
                         repeat = keyboard.nextLine();

                         if(input.equalsIgnoreCase("no")); {
                           System.out.println("Thanks for playing!"); }

                           System.out.println(wins + " wins");
                           System.out.println(losses + " losses");
                         }
}

正在跳过询问我是否想要再玩一次,我不知道使用什么样的循环

2 个答案:

答案 0 :(得分:0)

如果没有你的代码,我认为这就是你需要的。

boolean doContinue = true;
do {
     //guess random number 6 times
     //do you want to continue?
     // yes -> doContinue = true;
     // no -> doContinue = false;
} while (doContinue );

答案 1 :(得分:0)

我建议你的循环像这样做一个do-while循环:

do {
    for (int i=0; i<6; i++){
        /*
            insert code for the guessing/checking/etc.
        */
    }
    System.out.print("Would you like to continue? [Y/n] ");
} while (scan.next().toUpperCase().charAt(0) != 'Y');