Pracuję nad moim pierwszym projektem Java implementującym klasę o nazwie "HeartRates", która przyjmuje datę urodzenia użytkownika i zwraca jej maksymalną i docelową wartość tętna. Wszystko w głównym programie testowym działa z jednym wyjątkiem, nie wiem, jak zatrzymać resztę kodu po wydrukowaniu wyjątku.Wystąpił wyjątek, ale program nadal działa.
Nie jestem pewien co do całej części kodu, w której wyjątek został złapany, ponieważ został skopiowany i wklejony z tego, co dał nam profesor. Jeśli ktoś może mi powiedzieć, jak zakończyć program po wystąpieniu błędu, lub wydrukować niestandardowy komunikat o błędzie i zatrzymać dalsze wykonywanie programu, byłbym wdzięczny.
Oto kod:
import java.util.Scanner;
import java.util.GregorianCalendar;
import javax.swing.JOptionPane;
public class HeartRatesTest {
public static void main(String[] args) {
HeartRates test= new HeartRates();
Scanner input = new Scanner(System.in);
GregorianCalendar gc = new GregorianCalendar();
gc.setLenient(false);
JOptionPane.showMessageDialog(null, "Welcome to the Heart Rate Calculator");;
test.setFirstName(JOptionPane.showInputDialog("Please enter your first name: \n"));
test.setLastName(JOptionPane.showInputDialog("Please enter your last name: \n"));
JOptionPane.showMessageDialog(null, "Now enter your date of birth in Month/Day/Year order (hit enter after each): \n");
try{
String num1= JOptionPane.showInputDialog("Month: \n");
int m= Integer.parseInt(num1);
test.setMonth(m);
gc.set(GregorianCalendar.MONTH, test.getMonth());
num1= JOptionPane.showInputDialog("Day: \n");
m= Integer.parseInt(num1);
test.setDay(m);
gc.set(GregorianCalendar.DATE, test.getDay());
num1= JOptionPane.showInputDialog("Year: \n");
m= Integer.parseInt(num1);
test.setYear(m);
gc.set(GregorianCalendar.YEAR, test.getYear());
gc.getTime(); // exception thrown here
}
catch (Exception e) {
e.printStackTrace();
}
String message="Information for "+test.getFirstName()+" "+test.getLastName()+": \n\n"+"DOB: "+ test.getMonth()+"/" +test.getDay()+ "/"
+test.getYear()+ "\nAge: "+ test.getAge()+"\nMax Heart Rate: "+test.getMaxHR()+" BPM\nTarget Heart Rate(range): "+test.getTargetHRLow()
+" - "+test.getTargetHRHigh()+" BPM";
JOptionPane.showMessageDialog(null, message);
}
umieścić '' showMessageDialog' wewnątrz try {} 'bloku –