Question

In: Computer Science

In Java. Modify the attached GameDriver2 to read characters in from a text file rather than...

In Java. Modify the attached GameDriver2 to read characters in from a text file rather than the user. You should use appropriate exception handling when reading from the file. The text file that you will read is provided.

-------------------- Modify GaveDriver2.java --------------------

-----GameDriver2.java -----

import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;

/**
* Class: GameDriver
*
* This class provides the main method for Homework 2 which reads in a
* series of Wizards, Soldier and Civilian information from the user
* and creates the objects
*
*/
public class GameDriver2
{

/**
* Main method- Starting point of program
*
* @param args
*/
public static void main(String[] args)
{

// create needed variables
ArrayList characters = new ArrayList();

// YOU CHANGE THIS LINE to opening file Characters.txt - use appropriate exception handling
// don't
// just throw the exception
Scanner in = new Scanner(System.in);

// End first change

// HERE IS CODE THAT READS A LINE AND CREATES APPROPRIATE CHARACTER

while (in.hasNextLine())
{
// read in a line and parse into various attributes
String line = in.nextLine();

// parse based on comma
String[] data = line.split(", ");
String type = data[0];
String name = data[1];
int strength = Integer.parseInt(data[2]);
String weapon = data[3];
int magic = Integer.parseInt(data[4]);
  
// use this data to build appropriate GameCharacter based on type and add to ArrayList
// YOU ADD THIS CODE

}
// print array before hits or healing
for (GameCharacter g : characters)
{
System.out.println(g);
}

System.out.println();
System.out.println("After soldier takes a hit and civilian is healed");

// print contents of arrayList
for (int i = 0; i < characters.size(); i++)
{
GameCharacter g = characters.get(i);
// if a civilian - heal them
if (g instanceof Civilian)
{
g.heal(5);
}
// else if a soldier - takes a hit
else if (g instanceof Soldier)
{
g.takeHit(5);
}

System.out.println(g);
}

}

}

----- GameCharacter.java -----

  


/**
* Class: GameCharacter
*
* This class provides a parent class for characters to be created for
* our game.
*
*/
public class GameCharacter {
   // attributes for all GameCharacters
   private String name;
   private int strength;

   /**
   * Name Setter
   *
   * @param name the name to set
   */
   public void setName(String name) {
       this.name = name;
   }

   /**
   * Strength setter method
   *
   * Makes sure strength is a legit value. Ignores otherwise
   *
   * @param strength the strength to set
   */
   public void setStrength(int strength) {
       if (strength > 0 && strength <= 18) {
           this.strength = strength;
       } else {
           this.strength = 12; // default number I made up
       }
   }

   /**
   * All arg constructor
   *
   * @param name
   * @param strength
   */
   public GameCharacter(String name, int strength) {
       super();
       this.name = name;
       setStrength(strength);
   }

   /**
   * No-arg (default) constructor
   */
   public GameCharacter() {
       this.strength = 15;
       this.name = "TBD";
   }

   /**
   * Getter method for name
   *
   * @return the name
   */
   public String getName() {
       return name;
   }

   /**
   * Getter method for strength
   *
   * @return the strength
   */
   public int getStrength() {
       return strength;
   }

   /**
   * method: takeHit() Method called when character is attacked and has lost
   * strength
   *
   * @param int amount
   */
   public void takeHit(int amount) {
       strength = strength - amount;
       if (strength < 0) {
           strength = 0;
       }
   }

   /**
   * Method: heal()
   *
   * Method called as character heals from a hit
   *
   * @param int amount
   *
   */
   public void heal(int amount) {
       strength = strength + amount;
       if (strength > 18) {
           strength = 18;
       }
   }

}

----- Characters.txt -----

Soldier, Sol, 14, Sword, 50
Wizard, Wiz, 5, Staff, 444
Civilian, Civ, 18, Words, 3
Soldier, Joe, 3, Gun, 0
Wizard, Gandalf, 10, Wand, 500
Civilian, Frodo, 16, Money, 40

I can provide the 3 child classes (Soldier, Wizard, Civilian) if needed as the code exceed the text limits.

Solutions

Expert Solution

import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
import game.GameCharacter;
import java.io.BufferedReader;
import java.io.File;  
import java.io.FileNotFoundException;  
import java.io.FileReader;
import java.io.IOException;

public class GameDriver2
{


public static void main(String[] args) throws IOException
{


ArrayList<GameCharacter> characters = new ArrayList<>();

 File file = null;
FileReader fr=null;
BufferedReader br=null;
try
{
    file = new File("C:\\Users\\Gaurang\\Desktop\\Characters.txt");
    fr = new FileReader(file);
    br=new BufferedReader(fr);
    String line;
        while ((line=br.readLine())!=null)
            {
            
            

                    // parse based on comma
                    String[] data = line.split(", ");
                    String type = data[0];
                    String name = data[1];
                    int strength = Integer.parseInt(data[2]);
                    String weapon = data[3];
                    int magic = Integer.parseInt(data[4]);

                    // use this data to build appropriate GameCharacter based on type and add to ArrayList
                    // YOU ADD THIS CODE
                    if(type=="Soldier")
                    {
                            Soldier soldier = new Soldier(name,strength);
                            characters.add(soldier);
                    }
                    else if(type=="Civilian")
                    {
                            Civilian civ = new Civilian(name,strength);
                            characters.add(civ);
                    }
                    else if(type=="Wizard")
                    {
                        Wizard wiz = new Wizard(name,strength);
                        characters.add(wiz);

                    }
    
            }
}

catch(FileNotFoundException  exc)
        {
            
           if(!file.exists())
           {
               System.out.println("The Given File Does Not Exists");
           }
        }

finally
{
    fr.close();
    br.close();
}





 //print array before hits or healing
for (GameCharacter g : characters)
{
System.out.println(g);
}

System.out.println();
System.out.println("After soldier takes a hit and civilian is healed");

// print contents of arrayList
for (int i = 0; i < characters.size(); i++)
{
GameCharacter g = characters.get(i);
// if a civilian - heal them
if (g instanceof Civilian)
{
g.heal(5);
}
// else if a soldier - takes a hit
else if (g instanceof Soldier)
{
g.takeHit(5);
}

System.out.println(g);
}

}

}

Related Solutions

Please write a java program to write to a text file and to read from a...
Please write a java program to write to a text file and to read from a text file.
1) How do you read the contents of a text file that contains whitespace characters as...
1) How do you read the contents of a text file that contains whitespace characters as part of its data? 2) What capability does the fstream data type provide that the ifstream and ofstream data types do not? 3) What header file do you need to include in a program that performs file operations? 4) What data type do you use when you want to create a file stream object that can write data to a file? 5) What data...
How to read a text file and store the elements into a linked list in java?...
How to read a text file and store the elements into a linked list in java? Example of a text file: CS100, Intro to CS, John Smith, 37, 100.00 CS200, Java Programming, Susan Smith, 35, 200.00 CS300, Data Structures, Ahmed Suad, 41, 150.50 CS400, Analysis of Algorithms, Yapsiong Chen, 70, 220.50 and print them out in this format: Course: CS100 Title: Intro to CS Author: Name = John Smith, Age = 37 Price: 100.0. And also to print out the...
Modify this program so that it takes in input from a TEXT FILE and outputs the...
Modify this program so that it takes in input from a TEXT FILE and outputs the results in a seperate OUTPUT FILE. (C programming)! Program works just need to modify it to take in input from a text file and output the results in an output file. ________________________________________________________________________________________________ #include <stdio.h> #include <string.h> // Maximum string size #define MAX_SIZE 1000 int countOccurrences(char * str, char * toSearch); int main() { char str[MAX_SIZE]; char toSearch[MAX_SIZE]; char ch; int count,len,a[26]={0},p[MAX_SIZE]={0},temp; int i,j; //Take...
in java Read in a word and display the requested characters from that word in the...
in java Read in a word and display the requested characters from that word in the requested format. Write a Java program that ● prompts the user for a word and reads it, ● converts all characters of the input word to uppercase and display the word with a double quotation mark ( " ) at the start and end of the word, ● displays the word with all characters whose index is odd in lower case and for the...
C++ Parse text (with delimiter) read from file. If a Text file has input formatted such...
C++ Parse text (with delimiter) read from file. If a Text file has input formatted such as: "name,23" on every line where a comma is the delimiter, how would I separate the string "name" and integer "23" and set them to separate variables for every input of the text file? I am trying to set a name and age to an object and insert it into a vector. #include <iostream> #include <vector> #include <fstream> using namespace std; class Student{    ...
I need to write a java program (in eclipse) that will read my text file and...
I need to write a java program (in eclipse) that will read my text file and replace specific placeholders with information provided in a second text file. For this assignment I am given a text file and I must replace <N>, <A>, <G>, with the information in the second file. For example the information can be John 22 male, and the template will then be modified and saved into a new file or files (because there will be multiple entries...
Read a text file into arrays and output - Java Program ------------------------------------------------------------------------------ I need to have...
Read a text file into arrays and output - Java Program ------------------------------------------------------------------------------ I need to have a java program read an "input.txt" file (like below) and store the information in an respective arrays. This input.txt file will look like below and will be stored in the same directory as the java file. The top line of the text represents the number of people in the group for example. the lines below it each represent the respective persons preferences in regards...
Write a Java application "WellFormedExpression.java". Start with the file attached here. Please read the comments and...
Write a Java application "WellFormedExpression.java". Start with the file attached here. Please read the comments and complete the function 'isWellFormed()'. It also has the main() to test the function with several input strings. Feel free to change and add more tests with different kinds of input data for correct implementation. Note that you need MyStack.java and Stackinterface.java in the same package. WellFormedExpression.java package apps; public class WellFormedExpression {    static boolean isWellFormed(String s) {        /**** Create a stack...
Complete the program to read in values from a text file. The values will be the...
Complete the program to read in values from a text file. The values will be the scores on several assignments by the students in a class. Each row of values represents a specific student's scores. Each column represents the scores of all students on a specific assignment. So a specific value is a specific student's score on a specific assignment. The first two values in the text file will give the number of students (number of rows) and the number...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT