重复数据验证

时间:2013-04-11 08:22:54

标签: java

我需要问三个级别的薪水。 1级必须至少为65k,2级必须至少为60k。等级1也必须至少等于等级2的110%。等级2也必须至少等于等级3的120%。我只是从等级1和等级2开始,因为如果我能弄明白,我可以弄清楚等级3这就是我所拥有的:

    do {
        System.out.println("Please enter the full time employee payscale level 1 rate: ");
        fullTimePay1 = input.nextInt();
    } while (fullTimePay1 < 65000);

    do {
        System.out.println("Please enter the full time employee payscale level 2 rate: ");
        fullTimePay2 = input.nextInt();
        } while (fullTimePay2 < 60000);

    do {
        System.out.println("Please enter the full time employee payscale level 1 rate: ");
        fullTimePay1 = input.nextInt();
        System.out.println("Please enter the full time employee payscale level 2 rate: ");
        fullTimePay2 = input.nextInt();
    } while (fullTimePay1 < (fullTimePay2 * 1.1));

但它只是一遍又一遍地重复(我在此代码之后有一个从不执行的print语句)。谁能告诉我为什么,也许可以帮助我的代码?

1 个答案:

答案 0 :(得分:0)

正如您的代码所示,当我输入例如100000和70000(两次)循环终止;你可能会混淆哪个值应该更大(或者连续尝试不止一次)?

您的代码将无法正常运行,因为您没有在第三个循环上执行65k和60k验证,并且您还要求每次输入两次而不是一次(正确输入时)(执行时检查条件) 循环之后,而不是之前(while循环会这样做),所以第三个循环将询问用户输入,无论值是什么)。

用以下代替3循环应该有效:

do {
  do {
    System.out.println("Please enter full time employee payscale level 1 rate:");
    fullTimePay1 = input.nextInt();
  } while (fullTimePay1 < 65000);
  do {
    System.out.println("Please enter full time employee payscale level 2 rate:");
    fullTimePay2 = input.nextInt();
  } while (fullTimePay2 < 60000);
} while (fullTimePay1 < (fullTimePay2 * 1.1));

但是,如果允许,那么在第二个上验证110%对我来说更有意义:

do {
  System.out.println("Please enter full time employee payscale level 1 rate:");
  fullTimePay1 = input.nextInt();
} while (fullTimePay1 < 66000); // 'cause min(1) = 1.1*min(2) = 1.1*60000 = 66000
do {
  System.out.println("Please enter full time employee payscale level 2 rate:");
  fullTimePay2 = input.nextInt();
} while (fullTimePay2 < 60000 || fullTimePay1 < (fullTimePay2 * 1.1));