나는 다음과 같은 수행이 자바 프로그램을 만드는거야 :자바 여러 조건을 가진 루프 동안 : 데이터 유효성 검사 문제
/*Prompt user to enter miles and miles per hour.
Display approximate travel time in hours and minutes.
Accept decimal entries.
Prompt user to continue (if user enters “y” or “Y”).
*Must* perform data validation: a. only numbers, b. miles range (> 0 and no more than 3000), c. MPH (> 0 and no more than 100).
Hint: Use integer arithmetic and division and modulus operators to calculate hours and minutes.
Example: miles: 100, MPH 65: 1 hr(s) 32 min(s)*/
나는 정확한 최종 결과를 가질 수 있어요,하지만 나는이 문제에가 오전 데이터 유효성 검사. 문자 입력, 0보다 작은 숫자 또는 3000보다 큰 숫자 입력이있을 때 오류 응답이 발생해야합니다 (MPH를 묻는 메시지가 표시 될 때도 작동해야하지만 편집 할 것임). 마일에 대한 데이터 검증이 완료되었을 때).
하나의 while 루프에 모든 유효성 검사를 끝내고 처음 두 조건 (문자와 3000보다 큰 숫자가 입력되는 경우)이 제대로 작동하지만 세 번째 조건과 올바른 경우 입력 (0 ~ 3000 사이의 숫자)이 입력되면 프로그램은 즉시이를 승인하지 않고 입력을 여러 번 입력해야합니다 (그림을 넣을 수 없기 때문에 터미널 출력의 마지막 코드 블록을 참조하십시오).
안내해 주셔서 감사합니다.
import java.util.Scanner;
public class timetravel
{
public static void main(String[] args)
{
double miles;
double MPH;
double calculate;
double hours;
double minutes;
char answer;
System.out.println("This program displays the approximate travel time in hours and minutes.");
System.out.println("It accepts decimal entries and MUST perform data validation: a. only numbers, b. miles range (>0 and no more than 3000), c. MPH (> 0 and no more than 100).");
System.out.println();
do {
Scanner sc = new Scanner(System.in);
System.out.print("Enter miles: ");
while((!sc.hasNextDouble()) || sc.nextDouble() > 3000 || sc.nextDouble() < 0){
System.out.println("Not a valid input.");
System.out.print("Please enter only numbers greater than 0 and less than 3001: ");
sc.next();
}
miles = sc.nextDouble();
System.out.print("Enter MPH: ");
while(!sc.hasNextDouble()){
System.out.println("Not a valid input.");
System.out.print("Please enter only numbers greater than 0 and less than 3001: ");
sc.next();
}
MPH = sc.nextDouble();
calculate = (miles/MPH);
hours = Math.floor(calculate);
minutes = (calculate * 60) % 60;
minutes = Math.floor(minutes);
System.out.println("Miles: " + miles + ", MPH " + MPH + ": " + hours + " hr(s) " + minutes + " min(s)");
System.out.println("This is calculate: " + calculate);
System.out.println("Would you like to continue?: ");
answer = sc.next().charAt(0);
answer = Character.toUpperCase(answer);
} while(answer == 'Y');
}
}
터미널 출력
Not a valid input.
Please enter only numbers greater than 0 and less than 3001: 3002
Not a valid input.
Please enter only numbers greater than 0 and less than 3001: -1
-1
-1
Not a valid input.
Please enter only numbers greater than 0 and less than 3001: 30
30
30
30
Enter MPH: