2017-09-25 107 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

因此,在第三次嘗試之後,程序應打印出「您已被解僱」。我應該怎麼做? –