如果java中的用户输入为yes,则让脚本再次运行

时间:2017-09-24 18:22:42

标签: java

我需要帮助才能使得整个脚本从头开始循环,如果用户在结尾处输入y并且如果用户在结尾处键入n则脚本结束。谢谢你的帮助。

package test123;

import java.util.Scanner;

public class test321 {

public static void main(String[] args) {
    int n = 1;  
        int c;
        String playAgain;

do {
    System.out.println("Enter a number");
    Scanner scanner = new Scanner(System.in);
     n = scanner.nextInt();

      if ( n < 0 )
         System.out.println("Number cant be a negative.");
      else
      {
         int x=n*(n-1)*(n-2);

         System.out.println("Factorial= "+x);

        System.out.println("Do you want to continue? (y/n):");
         playAgain = scanner.nextLine();

          }while (!playAgain.equals("y"));
       }
    }
}

2 个答案:

答案 0 :(得分:0)

package test123;

import java.util.Scanner;

public class test321 {

public static void main(String [] args){

    int n = 1;  
    int c;
    String playAgain;

     do {

          System.out.println("Enter a number");
          Scanner scanner = new Scanner(System.in);
          n = scanner.nextInt();

  if ( n < 0 )
     System.out.println("Number cant be a negative.");
  else
  {
     int x=n*(n-1)*(n-2);

     System.out.println("Factorial= "+x);

    System.out.println("Do you want to continue? (y/n):");
     playAgain = scanner.nextLine();
   } // end else
 } // end do
 while (playAgain.equals("y"));

}// end main

} //结束课

答案 1 :(得分:-1)

更改

while (!playAgain.equals("y"));

while (!playAgain.equals("n"));