2017-09-25 56 views
0

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

如何在第三次无效尝试后停止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 
     } 
    } 
} 
+0

JavaScript不是JAVA。 – PHPglue

回答

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;指令下面的代码。
+0

因此,第三次尝试后,该程序应打印出“你被解雇”。我应该怎么做? –

+0

只需用你想要的信息替换错误信息,然后使用'return;'退出主函数。答案更新后,您的评论 – Al1

+0

它说已终止,但仍没有打印出“你被解雇!” 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; –

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; 
     } 

    } 
+0

由于输入应该是不正确的,OP可能想要退出整个功能,而不是简单地打破循环。使用'break',代码将继续运行,这不是预期的行为。无关,但如果我可以,请在发布答案时注意格式化 – Al1

+0

因此,在第三次尝试之后,程序应打印出“您已被解雇”。我应该怎么做? –