首页 > 解决方案 > “no”输入函数在 while 循环 Java 中不起作用

问题描述

标签: java

解决方案


这行得通。我已将行更改YoN = console.nextLine();YoN = input.nextLine();.

  import java.util.*;
  public class rockPaperScissors
  {
      public static void main(String[] args) 
      {
          Scanner input = new Scanner(System.in);
          System.out.println("Do you want to play a round of rock, paper, scissors? Type yes or no.");
      String YoN = input.nextLine();//yes or no repsonse
      int Uwin = 0;//user win count
      int Cwin = 0;//computer win count
      int tie = 0;//tie count
      if (YoN.equalsIgnoreCase("yes"))
      {
          while (!YoN.equalsIgnoreCase("no"))
          {
              System.out.println("Type 1 for rock, 2 for paper, and 3 for scissors.");
              Scanner console = new Scanner(System.in);
              int choice = console.nextInt();
              while (choice < 1 || choice > 3)
              {
                  System.out.println("Invalid entry. Please type 1, 2, or 3.");
                  choice = console.nextInt();
              }
              Random r = new Random();
              int comp = r.nextInt(3) + 1;
              if (comp == 1)
              {
                  System.out.println("Computer chose rock.");
              }
              if (comp == 2)
              {
                  System.out.println("Computer chose paper.");
              }
               if (comp == 3)
              {
                  System.out.println("Computer chose scissors.");
              }
              if ((choice == 3 && comp == 1) || (choice == 2 && comp == 3) || (choice == 1 && comp == 2))
              {
                  Cwin++;
              }
              else if ((choice == 2 && comp == 1) || (choice == 3 && comp == 2) || (choice == 1 && comp == 3))
              {
                  Uwin++;
              }
              else
              {
                  tie++;
              }
              System.out.println("Computer wins: " + Cwin + "\nYour wins: " + Uwin + "\nTies: " + tie);
              System.out.println("\n\nDo you want to play a round of rock, paper, scissors?");
              YoN = input.nextLine();
              //console.nextLine();
              if (YoN.equalsIgnoreCase("no"))
              {
                  System.out.println("Computer wins: " + Cwin + "\nYour wins: " + Uwin + "\nTies: " + tie);
              }
          }
      }
      else if (YoN.equalsIgnoreCase("no"))
      {
          System.out.println("Thank you!");
      }
      else
      {
          System.out.println("Invalid entry. Please type yes or no.");
          YoN = input.nextLine();
      }
  }
  }

推荐阅读