"Specify Max Time"에 대한 do while 루프에 유효한 입력이 주어지면 루프를 중단하기 전에 오류 메시지가 계속 표시됩니다.
Scanner console = new Scanner(System.in);
System.out.println("Specify city : ");
String city;
//loops if input is anything but New York or Paris
do {
city = console.next();
if (!city.equals("New York") && !city.equals("Paris")) {
System.out.println("Enter valid city");
}
} while (!city.equals("New York") && !city.equals("Paris"));
System.out.println("Specify Max Time (HH:MM) : ");
String time;
//loops if input not is in 24 hour format
do {
time = console.next();
if (!time.matches("[0-9]{2}:[0-9]{2}")); {
System.out.println("Enter Valid Time (HH:MM) :");
}
} while (!time.matches("[0-9]{2}:[0-9]{2}"));
패턴 일치를 크게 단순화 할 수 있습니다.
do {
// Your stuff goes here
} while(!time.matches("[0-9]{2}:[0-9]{2}"));
// --------------------^^^^^^^^^^^^^^^^^
// Easier, don't you think?
또한 시간 및 분 값이 유효한지 확인해야합니다. 시간 값은 0에서 23 사이 여야하고 분 값은 0에서 59 사이 여야합니다.
코드를 확인하고 유효성을 검사하는 데 충분한 시간이 있습니다. 나는 관대하다고 느끼고 지금 당장 할 일이 없기 때문에 문제에 대한 내 자신의 테스트 된 해결책을 넣었습니다 .
import java.util.Scanner;
public class SO_Example_20151205_01 {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
String pattern = "[0-9]{2}:[0-9]{2}"; // The pattern you'll use to validate if the time is valid
String time; // The input variable
boolean valid_time = false; // A flag to break the loop. Initialized to false
int hour, minute;
// I prefer to use a 'while' loop in this case.
// The loop will break if the valid_time variable is true
while(!valid_time) {
System.out.print("Enter time (HH:MM):\t");
time = console.next();
// Check if the input matches the pattern:
if(time.matches(pattern)) {
// Now, check if the input values are valid
hour = Integer.parseInt(time.substring(0,2));
minute = Integer.parseInt(time.substring(3,5));
if(hour >= 0 && hour <= 24 && minute >= 0 && minute < 60) {
valid_time = true;
} else {
System.out.println("\nYou've entered a valid pattern, but the values are invalid!\n Please try again");
}
} else {
System.out.println("\nYou entered a non recognized pattern. Please try again\n");
}
}
System.out.println("Done!");
}
}
while
루프를 사용하면 두 번 이상 작성하는 것을 피할 수 있습니다. 또한 내가 사용하는 패턴을 확인하십시오 ... 작동합니다!
나는 자주 부울 플래그를 사용하여 내 루프를 끊습니다 (아마도 더 깨끗한 솔루션은 아니지만 작동하며 루프가 중단 될 위치와시기를 정확하게 볼 수 있습니다). 또한 입력 한 시간과 분에 대한 유효성 검사를 추가했습니다.
이 솔루션은 의도적으로 장황합니다. 정확히 제가 원하는 것입니다. 이렇게하면 진행 상황을 더 쉽게 확인할 수 있습니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다