简体   繁体   中英

How do I get continuous user input?

I need a help trying to set my code to continuously receive user input for factorial numbers. It will produce a question and intake the user input but only once. I want it to continue asking the user for that input.

I tried to do a while loop however nothing shows up.

import java.util.Scanner;
public class FactorialRecursion
{

    public static void main(String[] arg)
    {
            Scanner scan = new Scanner(System.in);
            long userInput;

            System.out.println("Please enter a number you would like find the factorial of.");
            userInput = scan.nextLong();
            long fc = FactorialRecursion.fact(userInput);
            System.out.println("Factorial = " + fc);
    }



    public static long fact(long x)
    {
            if (x <= 0)
                return 1;
            else
                return FactorialRecursion.fact(x - 1) * x;
    }

}

The output is correct but I want my program to continue asking for that input.

public class Test{
 public static void main(String []args) {
    int num;
    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter numbers!");

    while((num = scanner.nextInt()) > 0) {
        System.out.println("Receiving...");
    }

    {
        System.out.println("Negative number Stopping the system...");
        System.exit(1);
    }
}

}

Without knowing how you were looping before (my assumption is that you were including the scanner instantiation which might have caused an issue), here is an implementation that I believe will work for you. This will continue to scan for a number, unless a negative number is entered. Therefore you have an actual exit condition that doesn't make sense for factorial, and the user can repeatedly enter and find the factorial of positive numbers.

In order for this to work, I instantiated the userInput variable to be 0 so that the loop will run for the first time. You can alteratively use a do...While loop in stead, but I prefer this method generally.

public static void main(String[] arg)
  {

    Scanner scan = new Scanner(System.in);

    long userInput=0;
    while(userInput >=0)
    {
      System.out.println("Please enter a number you would like find the factorial of. Enter a negative number to exit.");

      userInput = scan.nextLong();

      long fc = FactorialRecursion.fact(userInput);

      System.out.println("Factorial = " + fc);
    }
  }

If you would like to see what the do-while loop would look like, just comment and I'll put a little more time into answering this. Also any questions you have comment away!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM