[50 p.] Write a Java program (Lab06B_Q2_lastname.java) that inputs a file name f
ID: 3641040 • Letter: #
Question
[50 p.] Write a Java program (Lab06B_Q2_lastname.java) that inputs a file name from user,reads month names from the file and outputs how many days are in each month.
Write a static method (monthDays) which gets a file name as parameter, reads the contents of
the file and prints the month names and their respective number of days as seen in the sample
run.
Write a static method (getDaysInMonth) which gets a month name as parameter, and returns
the number of days in that month. Do not use long nested if's in this method. Use two arrays,
one array holding the month names and the other array keeping the number of days in the
months. Then search the month name given as parameter in the month-names array.
Input file contains the number of queried months in the first line and the month names in the
subsequent lines (see sample file content below).
Sample text file contents: lab06b_q2.txt
5
July
April
December
February
January
Sample Runs: (User inputs are shown in red.)
Enter filename: lab06b_q2.txt
There are 31 days in July
There are 30 days in April
There are 31 days in December
There are 28 days in February
There are 31 days in January
Explanation / Answer
import java.io.FileReader;
import java.util.Scanner;
public class Lab06B_Q2_yourlastname {
public static void main(String[] args) {
String [] monthNames = {
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
};
int [] monthDays = {
31, 28, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31
};
Scanner in = new Scanner(System.in);
String fileName;
int count;
String mName;
int mDays;
//Get file name
System.out.print("Enter file name: ");
fileName = in.next();
//Open file
try {
in = new Scanner(new FileReader(fileName));
}
catch (Exception e) {
System.out.println("ERROR: File NOT found " + e.getMessage());
System.exit(1);
}
//Read the number of queried months
count = in.nextInt();
//Get month days
for (int i = 0; i < count; i++) {
mName = in.next();
mDays = 0;
for (int m = 0; m < monthNames.length; m++) {
if (mName.compareTo(monthNames[m]) == 0) {
mDays = monthDays[m];
break;
}
}
System.out.println("There are " + mDays + " days in " + mName);
}
//Close file
in.close();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.