//by :tlc
import java.util.Scanner;
public class assignment2 {
public static int t1;
public static int t2;
public static int x;
public static int y1;
public static int m1;
public static int d1;
public static int y2;
public static int m2;
public static int d2;
public static void date1() {
Scanner scanner = new Scanner (System.in);
System.out.println("Please enter the first date \n");
System.out.println ("Please enter the year: ");
y1=scanner.nextInt();
System.out.println("Please enter the month: ");
m1=scanner.nextInt();
System.out.println("Please enter the day: \n");
d1=scanner.nextInt();
}
public static void date2() {
Scanner scanner = new Scanner (System.in);
System.out.println("Please enter the second date \n");
System.out.println ("Please enter the year: ");
y2=scanner.nextInt();
System.out.println("Please enter the month: ");
m2=scanner.nextInt();
System.out.println("Please enter the day: \n");
d2=scanner.nextInt();
}
public static void finaldate() {
x = Math.abs(t1-t2);
}
public static void main(String[] args) {
date1();
if (m1==1 + 3 + 5 + 7 + 8 + 10 + 12){
t1 = ((365*y1)+d1+31);}
else
if (m1==2) {
t1 = ((365*y1)+d1+28);}
else
if (m1==4 + 6 + 9 + 11); {
t1 = ((365*y1)+d1+30);}
date2();
if (m2==1 + 3 + 5 + 7 + 8 + 10 + 12){
t2 = ((365*y2)+d2+31);}
else
if (m2==2) {
t2 = ((365*y2)+d2+28);}
else
if (m2==4 + 6 + 9 + 11); {
t2 = ((365*y2)+d2+30);}
finaldate();
System.out.println("The difference between the two dates is: " + x + " days.");
}
}
How would I set a catch a false input (ex: not a integer) and have the program display an error message followed by a loop that would return to the beginning of the program? I’ve been struggling with this for a while now.
All help appreciated! 🙂
there are 2 way depending on how the control flow is managed
with exceptions as control flow (the case with Scanner)
with a sentinel as control flow (not the case with Scanner but provided for future reference)