如何在第3次无效尝试后停止While循环?

时间:2017-09-25 22:36:24

标签: java while-loop do-while

所以我有一个关于停止循环的大问题。主要问题是我必须在用户输入无效3次后停止while循环。但是,我不知道该怎么做。

如何在第3次无效尝试后停止while循环?

我应该使用哪些代码?

import java.text.DecimalFormat;
import java.util.Scanner;

public class CalculatePay {

    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);

        String Name = " ";
        int hours;
        double payRate;
        char F;
        char P;
        char T;
        char repeat;
        String input = " ";

        double grossPay;

        System.out.print("What is your name? ");
        Name = reader.nextLine();
        System.out.print("How many hours did you work? ");
        hours = reader.nextInt();
       while (hours < 0 || hours > 280) 
    {
            System.out.println("That's not possible, try again!");
            hours = reader.nextInt();
          attempt++;
         if(attempt == 3)
         System.out.println("You are Fired!");

          {
             return;
          }

        }
        System.out.print("What is your pay rate? ");
        payRate = reader.nextDouble();
        System.out.print("What type of employee are you? ");
        F = reader.next().charAt(0);


        grossPay = hours * payRate;
        DecimalFormat decFor = new DecimalFormat("0.00");

        switch (F){
            // irrelevant for the question
        }
    }
}

2 个答案:

答案 0 :(得分:0)

我假设这是你想要做的......

int attempt = 0;
while (hours < 0 || hours > 280) 
{
        System.out.println("That's not possible, try again!");
        hours = reader.nextInt();
      attempt++;
     if(attempt >= 3)
      {
         break;
      }

    }

答案 1 :(得分:0)

像亚当建议的那样,你需要一个计数器,例如:

    int attempt = 0;
    while (hours < 0 || hours > 280) {
        System.out.println("That's not possible, try again!");
        hours = reader.nextInt();
        attempt++;

        // do something if you reach the limit. The >= comparison is 
        // useless before attempt will never go over 4.
        if(attempt == 3){
            // notify the user that something wrong happened
            System.out.println("Your error message here");

            // exit the main function, further code is not processed
            return;
        }
    }

我建议打印一条消息并返回。有关您的信息,其他选项可以是:

  • 使用throw new MaxAttemptReachedException();
  • 抛出异常
  • 退出while循环,但继续使用break;指令处理以下代码。