简体   繁体   English

在 java 中使用 3 个验证参数进行输入验证

[英]Input validation with 3 validation parameters in java

I have this piece of code to validate an input, this input is relative to a bet made by an user我有这段代码来验证输入,这个输入与用户的赌注有关

  • it needs to be an int它必须是一个 int
  • it needs to be greater than 0它需要大于 0
  • it needs to be lower than the credits available (the user credits)它需要低于可用的信用(用户信用)
  1. if the user writes a string it should say: input + " is not a valid number"如果用户写了一个字符串,它应该说:输入+“不是一个有效的数字”
  2. if the user writes an int below or equals to zero it should continuously saying: "Please enter a positive number: "如果用户在下面写一个 int 或等于零,它应该不断地说:“请输入一个正数:”
  3. if the user writes an int higher than the credits available it should say: "not enough credits"如果用户写的 int 高于可用的积分,它应该说:“没有足够的积分”

the code I have right now is the following:我现在拥有的代码如下:

Scanner scanner = new Scanner(System.in);
int number;
do {
    System.out.print("Please enter a positive number: ");
    while (!scanner.hasNextInt()) {
        String input = scanner.next();
        System.out.printf(input + " is not a valid number.\n");
    }
    number = scanner.nextInt();
} while (number < 0);

System.out.printf("You have entered the number " + number);

I have the 1. and 2. figure it out with this code, but I can't for nothing add the third (3.) statement as it asks for double the same input or it gives an error InputMismatchException because it suppose to be an integer, but on test sometimes does that.我有 1. 和 2. 用这段代码弄清楚,但我不能无缘无故地添加第三 (3.) 语句,因为它要求双倍相同的输入,或者它给出错误 InputMismatchException 因为它假设是integer,但在测试中有时会这样做。

the number is suppose to be the bet这个数字应该是赌注

Please help xD请帮忙xD

You logic is rather convoluted and hard to follow.您的逻辑相当复杂,难以理解。 I think after this assignment you should ask for some help and find a better way to structure this code.我认为在完成这项任务之后,您应该寻求一些帮助并找到一种更好的方法来构建此代码。 (For now, instructors usually require you to turn in your own work so I'm not going to try to change your code.) (目前,讲师通常会要求您上交自己的作业,因此我不会尝试更改您的代码。)

The way you have the code now you'll have to do the final check in two parts.您现在拥有代码的方式必须分两部分进行最后检查。 First, check and then decide whether to print the error message.首先,检查然后决定是否打印错误信息。 Second, check and decide whether to continue the loop.其次,检查并决定是否继续循环。

do {
    System.out.print("Please enter a positive number: ");
    while (!scanner.hasNextInt()) {
        String input = scanner.next();
        System.out.printf(input + " is not a valid number.\n");
    }
    number = scanner.nextInt();
    if( number > credits )
        System.out.println( "Not enough credits." );
} while (number < 0 || number > credits);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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