java扫描程序输入验证导致循环提前结束

mm9b1k5b  于 2021-07-14  发布在  Java
关注(0)|答案(2)|浏览(346)

我用for循环填充一个双数组,循环运行用户在第4行输入的圈数。然而,正如我在图片中展示的:
我输入3圈,问题提示3次,但是我的数据验证会吃掉我正在寻找的输入之一。
我该怎么解决这个问题?我觉得这很简单。

  1. import java.util.Scanner;
  2. public class JK_FINALPRAC1 {
  3. public static void main(String[] args) {
  4. Scanner sc = new Scanner(System.in);
  5. System.out.println("Time-Trial Statistics Program\n");
  6. System.out.println("This program will ask you to input split-times for each lap or length of a race. The ");
  7. System.out.println("program will then calculate some basic statistics from the split-times.\n");
  8. System.out.print("Enter the number of laps or lengths in the race: ");
  9. int arraySize = sc.nextInt();
  10. Double[] lapArray = new Double[arraySize];
  11. System.out.println("Now input the elapsed time (split time) in seconds for each lap/length of the race.");
  12. int index = 1;
  13. double currentNum = 0.0;
  14. for(int i=0;i<arraySize;i++){
  15. System.out.print("Time for lap or length #" + index + ": ");
  16. currentNum = sc.nextDouble();
  17. if(currentNum > 0 && currentNum < 61){
  18. lapArray[i] = currentNum;
  19. index++;
  20. }else if(currentNum<0 || currentNum >60){
  21. System.out.println("Invalid input! Time must be between 0 and 60.");
  22. }
  23. }
  24. }

5kgi1eie

5kgi1eie1#

  1. double currentNum = 0.0;
  2. while (index < arraySize) {
  3. System.out.print("Time for lap or length #" + (index + 1) + ": ");
  4. currentNum = sc.nextDouble();
  5. if (currentNum > 0 && currentNum < 61) {
  6. lapArray[index] = currentNum;
  7. index++;
  8. } else if (currentNum < 0 || currentNum > 60) {
  9. System.out.println("Invalid input! Time must be between 0 and 60.");
  10. }
  11. }

因为您正在运行for循环,所以每次i都会递增(即使验证失败)。

uelo1irk

uelo1irk2#

它非常简单:为了确保你插入了一个双人而不吃一圈,把你的扫描仪输入线放在一个while循环中

  1. do{
  2. double x = scanner.nextDouble();
  3. }while(x < 0 || x > 60);

除非do while的条件为false,否则这将无法承受循环递增计数器。
为了打印验证:

  1. double x = scanner.nextLine();
  2. while( x < 0 || x > 60){
  3. //print message
  4. //scanner again
  5. }

相关问题