Java在验证时执行

时间:2014-12-14 03:57:15

标签: java validation do-while

我不明白为什么只有我的while语句正在工作,而且它没有转到有效整数的for语句。

import java.util.Scanner;

public class Factorial {

    public static void main(String[] args) {
        long posNumber;
        long x;
        long fact = 1;

        do {
            System.out.print("Enter a number between 2 and 15: ");
            Scanner in = new Scanner(System.in);
            posNumber = in.nextLong();
        } while (posNumber >= 2 || posNumber <= 15);


        for (x = 1; x <= posNumber; x++)
            fact = fact*x;
            System.out.println("Factorial of " +posNumber+ " is " +fact);

        }

    }

2 个答案:

答案 0 :(得分:1)

如果您计划在循环中获取数字,您应该尝试类似的事情:

Scanner in = new Scanner(System.in);
do {
    System.out.print("Enter a number between 2 and 15: ");
    posNumber = in.nextLong();

    for (x = 1; x <= posNumber; x++)
      fact = fact*x;
      System.out.println("Factorial of " +posNumber+ " is " +fact);
    }
} while (posNumber >= 2 || posNumber <= 15);

或者您可以更改条件(如果只运行一次):

while (posNumber < 2 || posNumber > 15);

答案 1 :(得分:0)

您希望程序继续询问用户该号码是否无效。这意味着如果它小于2或大于15.用以下内容替换你的while条件:

do {
    ...
} while (posNumber < 2 || posNumber > 15);

如果用户输入1,posNumber < 2将评估为true,导致循环重复并请求新号码。

如果用户输入3,则posNumber < 2posNumber > 15将评估为false,循环将中断,然后您的for循环将执行。