2014-10-19 60 views
0

很抱歉的基本問題 - 剛開始對JAVA讓用戶重新輸入值,如果值不正確

試圖驗證價值的用戶,進入前下一個值將輸入序列 - 程序運行到下一個if語句按順序,而不是要我重新輸入開始時間...

System.out.println("Enter start time in 24 hr format eg 0800 "); 
startTime = in.nextInt(); 

    if (startTime >=0000 && startTime <=2400) // verify hours 
     { 
     System.out.println ("thank you start hours entered "); 
     } 
    else 
     if (startTime >2400) // verify hours 
     { 
     System.out.println ("invalid start hours ! please re-enter "); 
     } 


System.out.println("Enter stop time in 24 hr format eg 1700 "); 

    stopTime = in.nextInt(); 

     if (stopTime >=0000 && stopTime <=2400) // verify hours 
     { 
     System.out.println ("thank you stop hours entered "); 
     } 
     else 
      if (stopTime >2400) 
      { 
      System.out.println ("invalid stop hours ! please re-enter "); 
      } 

    // proceed with rest of program 
+3

請注意,你的程序將接受像小時其中0099是不是有效的時間! – Sanchises 2014-10-19 09:25:39

回答

0

你應該看看一個while循環。例如。

do{ 
stopTime = in.nextInt(); 
} while (!(stopTime >=0000 && stopTime <=2400)); 
0

下面是完整的代碼是什麼,你打算做:

import java.util.Scanner; 

public class VerifyUserInput { 

    public static void main(String[] args) { 
     int hours = 0; 
     int minutes = 0; 
     Scanner sc = new Scanner(System.in); 
     boolean verifyStartTime=true; 

     // Get the input for start time and then Verify 
     do { 
      System.out.println("Enter Start Time :"); 
      System.out.println("Enter the Hour component from 00-24 :"); 
      hours =sc.nextInt(); 
      System.out.println("Enter the Minutes component from 00-60 :"); 
      minutes = sc.nextInt(); 
      String startTime = ""; 
      if(hours > -1 && hours <=24) { 
       if(minutes >-1 && hours <=60) { 
        startTime = hours+":"+minutes; 
        System.out.println("The Time entered is valid :"+startTime); 
       } 
       verifyStartTime = false; 
      }else { 
       System.out.println("Please Try Again !"); 
      } 
     }while(verifyStartTime); 

     boolean verifyEndTime=true; 
     // Get the input for End time and then Verify 
     do { 
      System.out.println("Enter End Time :"); 
      System.out.println("Enter the Hour component from 00-24 :"); 
      hours =sc.nextInt(); 
      System.out.println("Enter the Minutes component from 00-60 :"); 
      minutes = sc.nextInt(); 
      String endTime = ""; 
      if(hours > -1 && hours <=24) { 
       if(minutes >-1 && hours <=60) { 
        endTime = hours+":"+minutes; 
        System.out.println("The Time entered is valid :"+endTime); 
       } 
       verifyEndTime = false; 
      }else { 
       System.out.println("Please Try Again !"); 
      } 
     }while(verifyEndTime); 
    } 
} 

也可參加審議意見從@sanchises

+0

完美答案 - 謝謝 – 2014-10-19 12:34:24

+0

如果您對答案感到滿意,那麼將其作爲答案接受,因爲它會關閉答案以供其他觀衆使用。 – 2014-10-19 13:04:58

相關問題