对不起基本问题 - 刚开始使用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
答案 0 :(得分:0)
您应该查看while
循环。 E.g。
do{
stopTime = in.nextInt();
} while (!(stopTime >=0000 && stopTime <=2400));
答案 1 :(得分: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
的评论