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.
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...
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...
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...
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...
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...
Your task is to modify the program from the Java Arrays programming assignment to use text...
Your task is to modify the program from the Java Arrays programming assignment to use text files for input and output. I suggest you save acopy of the original before modifying the software. Your modified program should: contain a for loop to read the five test score into the array from a text data file. You will need to create and save a data file for the program to use. It should have one test score on each line of...
You are required to read in a list of stocks from a text file “stocks.txt” and...
You are required to read in a list of stocks from a text file “stocks.txt” and write the sum and average of the stocks’ prices, the name of the stock that has the highest price, and the name of the stock that has the lowest price to an output file. The minimal number of stocks is 30 and maximal number of stocks in the input file is 50. You can download a input file “stocks.txt” from Canvas. When the program...
Computer Science - Java Programming How do you read a text file and store three different...
Computer Science - Java Programming How do you read a text file and store three different pieces of information in the database when the given text file contains this info.: 12345 Computer Science Bob Stone 23456 Art James G. Ocean? These are written in the format as ID Class Name. I was going to take the three different pieces of information by separating them by spaces, but the number of spaces is random and I don't know how to adjust...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT