In: Computer Science
Important notes: Use Console I/O (Scanner and System.out) for all user I/O in this lab.
Do not hard code data file paths or filenames; always ask the user for them.
Complete the Monster Attack project by doing the following: In place of the driver used in homework 2, add a menu with a loop and switch (this is already done, ignore this).
The user must be able to add attacks, get a report on existing attacks, save a file, retrieve a file, and clear the list as many times as she wants in any order she wants.
Replace the array of MonsterAttacks with an ArrayList of MonsterAttacks. This will require changes in several methods. You will need to be able to handle any number of MonsterAttacks the user chooses to input.
Add a method to AttackMonitor that saves the list of attacks to a comma separated values file. Iterate through the list, and for each attack, get each field using the getters from MonsterAttack. Write each value to the file, following each one except the last with a comma. Save the date as a single String in the format MM/DD/YYYY. After you have written out all the data for one attack, write out a newline. Add an item to the main menu that calls this method.
Add a method that clears the list of monster attacks, then uses a Scanner to read data from a .csv file, uses it to instantiate MonsterAttack objects, and adds the attacks to the list. This method must be able to read the files you write out in the method described above. You will need to use String's split() method here. Add an item to the main menu that calls this method. Make sure you can input attack data, save to a file, quit the program, start the program again, read your output file, and show the data from the file.
Below is the original code that needs to be modified to meet the requirements stated above.
MonsterAttack
//side note- the date is incorrect here.. user is supposed to enter the date.. but that shouldn't matter.. still works
import java.util.Date;
class MonsterAttack {
private String monsterName;
private String attackLocation;
private double damagesInMillions;
private Date date;
public MonsterAttack(){
}
public MonsterAttack(String monsterName, String attackLocation,
double damagesInMillions, Date date){
this.monsterName = monsterName;
this.attackLocation = attackLocation;
this.damagesInMillions = damagesInMillions;
this.date = date;
}
public String getMonsterName(){
return monsterName;
}
public String getAttackLocation(){
return attackLocation;
}
public double getDamagesInMillions(){
return damagesInMillions;
}
public Date getDate(){
return date;
}
public void setMonsterName(String monsterName){
this.monsterName = monsterName;
}
public void setAttackLocation(String attackLocation){
this.attackLocation = attackLocation;
}
public void setDamagesInMillions(double damagesInMillions){
this.damagesInMillions = damagesInMillions;
}
public void setDate(Date date){
this.date = date;
}
public String toString(){
return " Monster named " + monsterName + " attacked in " +
attackLocation + " causing damages of " + damagesInMillions + "
dollars in " + date;
}
}
AttackMonitor
import java.util.Scanner;
import java.util.Arrays;
import java.util.Date;
public class AttackMonitor {
Scanner in = new Scanner (System.in);
MonsterAttack[] monsterArray = new MonsterAttack[5];
double[] damagesArray = new double[5];
static double damages = 0;
private void reportAttack(){
for (int i = 0; i < 5; i++){
// if (i == 0)
// System.out.println("press enter");
in.nextLine();
System.out.println("name");
String name = in.nextLine();
System.out.println("location");
String location = in.nextLine();
System.out.println("damage ");
double millions = in.nextDouble();
System.out.println("date");
damagesArray[i] = millions;
Date date = new Date();
damages = damages + millions;
MonsterAttack a = new MonsterAttack(name, location, millions,
date);
monsterArray[i] = a;
}
}
private void printAttacks(){
for (int x = 0; x < monsterArray.length; x++){
System.out.println(monsterArray[x]);
}
}
private void showDamages(){
for (int i = 0; i < damagesArray.length; i++){
System.out.println("damage for attack " + (i+1) + ": " +
damagesArray[i]);
}
System.out.println("total damages: " + damages);
System.out.println("average damage: " + damages/5);
}
private void findEarliestAttack () {
Date early = monsterArray[0].getDate();
for (int i = 0; i < monsterArray.length; i++){
if (early.compareTo(monsterArray[0].getDate()) > 0){
early = monsterArray[i].getDate();
}
}
System.out.println(early);
}
public void menu(){
String[] choices = { "Quit", "report attacks", "show attacks",
"show damages", "find earliest attack"};
int choice;
do {
System.out.println("Enter\n 0 to quit,\n 1 to report attacks, \n 2
to show attacks, \n 3 to show damages, \n 4 to find earliest
attack");;
choice = in.nextInt();
switch(choice){
case 0:
break;
case 1:
reportAttack();
break;
case 2:
printAttacks();
break;
case 3:
showDamages();
break;
case 4:
findEarliestAttack();
break;
}
} while (choice !=0);
}
}
MonitorDriver
import java.util.Scanner;
import java.util.Arrays;
import java.util.Date;
public class MonitorDriver{
public static void main (String[] args){
AttackMonitor test = new AttackMonitor();
test.menu();
}
}
Code:
// MonsterAttack.java
public class MonsterAttack {
// attributes
private int attackId;
private int day;
private int month;
private int year;
private String monsterName;
private String location;
private String reporter;
// constructor to initialize all fields
public MonsterAttack(int attackId, String dateString, String monsterName,
String location, String reporter) {
this.attackId = attackId;
this.monsterName = monsterName;
this.location = location;
this.reporter = reporter;
// splitting date field by / and extracting each term
String dateFields[] = dateString.split("/");
if (dateFields.length == 3) { // ensuring there is enough number of
// terms
month = Integer.parseInt(dateFields[0]);
day = Integer.parseInt(dateFields[1]);
year = Integer.parseInt(dateFields[2]);
}
}
//getters and setters
public int getAttackId() {
return attackId;
}
public void setAttackId(int attackId) {
this.attackId = attackId;
}
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public String getMonsterName() {
return monsterName;
}
public void setMonsterName(String monsterName) {
this.monsterName = monsterName;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getReporter() {
return reporter;
}
public void setReporter(String reporter) {
this.reporter = reporter;
}
//returns a string containing attack details
public String toString() {
String data = String
.format("Attack # %d: %s attacked %s on %02d/%02d/%04d. Reported by %s",
attackId, monsterName, location, month, day, year,
reporter);
return data;
}
}
// AttackMonitor.java
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
public class AttackMonitor {
// list of MonsterAttacks
private ArrayList<MonsterAttack> attacks;
// scanner to read user input
private Scanner scanner;
// constructor to initialize instance fields
public AttackMonitor() {
attacks = new ArrayList<MonsterAttack>();
scanner = new Scanner(System.in);
}
// method to interact with the user until user wishes to stop
public void monitor() {
int choice = 0;
// looping
while (choice != 6) {
// displaying menu, getting choice
System.out.println("\n1. Input info on a monster attack");
System.out.println("2. Show current list of monster attacks");
System.out.println("3. Delete a monster attack");
System.out.println("4. Save to file");
System.out.println("5. Load from file");
System.out.println("6. Exit");
System.out.print("## Enter your choice: ");
choice = Integer.parseInt(scanner.nextLine());
// handling choice
switch (choice) {
case 1:
inputMonster();
break;
case 2:
displayList();
break;
case 3:
deleteAttack();
break;
case 4:
saveToFile();
break;
case 5:
loadFromFile();
break;
}
}
}
// method to fetch details about a monster attack from user and add a new
// MonsterAttack entry to the list
public void inputMonster() {
System.out.print("Enter attack ID: ");
int attackId = Integer.parseInt(scanner.nextLine());
System.out.print("Date of attack (MM/DD/YYYY): ");
String dateStr = scanner.nextLine();
System.out.print("Monster name: ");
String monsterName = scanner.nextLine();
System.out.print("Location of attack: ");
String location = scanner.nextLine();
System.out.print("Reported by: ");
String reporter = scanner.nextLine();
// calling method to add monster, passing relevant info
addMonster(attackId, dateStr, monsterName, location, reporter);
System.out.println("Added successfully!");
}
// method to display the list
public void displayList() {
System.out.println("\nList of Monster Attacks:");
for (MonsterAttack attack : attacks) {
System.out.println(attack);
}
System.out.println();
}
// method to delete an attack
public void deleteAttack() {
if (attacks.size() > 0) {
displayList();
System.out.print("Enter ID of attack to delete: ");
int id = Integer.parseInt(scanner.nextLine());
boolean found = false;
for (int i = 0; i < attacks.size(); i++) {
if (attacks.get(i).getAttackId() == id) {
// found; removing
attacks.remove(i);
System.out.println("Removed successfully!");
found = true;
break;
}
}
// checking if not found
if (!found) {
System.out.println("Specified record not found!");
}
} else {
System.out.println("List is empty, nothing to delete!");
}
}
// method to add a monster attack by passing all required info
public void addMonster(int attackId, String dateString, String monsterName,
String location, String reporter) {
MonsterAttack attack = new MonsterAttack(attackId, dateString,
monsterName, location, reporter);
attacks.add(attack);
}
// method to store data from list into a file
public void saveToFile() {
System.out.print("Enter name of file to save the data: ");
String filename = scanner.nextLine();
try {
PrintWriter writer = new PrintWriter(new File(filename));
// looping and writing the contents in CSV format
for (MonsterAttack attack : attacks) {
writer.print(attack.getAttackId() + ",");
writer.print(attack.getMonth() + "/" + attack.getDay() + "/"
+ attack.getYear() + ",");
writer.print(attack.getMonsterName() + ",");
writer.print(attack.getLocation() + ",");
writer.println(attack.getReporter());
}
writer.close();
System.out.println("Saved!");
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
}
}
// method to load data from file into the list
public void loadFromFile() {
attacks.clear();
System.out.print("Enter name of file to load the data: ");
String filename = scanner.nextLine();
try {
Scanner fileScanner = new Scanner(new File(filename));
while (fileScanner.hasNext()) {
String line = fileScanner.nextLine();
String fields[] = line.split(",");
// ensuring that there are 5 terms
if (fields.length == 5) {
addMonster(Integer.parseInt(fields[0]), fields[1],
fields[2], fields[3], fields[4]);
}
}
System.out.println("Done loading!");
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
}
}
}
// MonsterAttackDriver.java
public class MonsterAttackDriver {
// method to add some hard coded test attacks to AttackMonitor object
private static void addTestAttacks(AttackMonitor monitor) {
monitor.addMonster(123, "10/25/2018", "Godzilla", "Tokyo", "Chang");
monitor.addMonster(176, "12/2/2016", "Thaanos", "New York", "Tony");
monitor.addMonster(178, "13/1/2014", "Ultron", "New York", "Jarvis");
}
public static void main(String[] args) {
// creating an AttackMonitor, adding test data, interacting with user
AttackMonitor attackMonitor = new AttackMonitor();
addTestAttacks(attackMonitor);
attackMonitor.monitor();
}
}