Inheritance: Correct initialization to store values ββin a HashMap
I am working with separate programs, one will read in a file .txt
, and then that same program will store the read values ββin another program containing HashMap
. The program containing HashMap
is called Hero.java
and is abstract class
. I have a program that extends this program called Cop.java
. With this in mind, I would like to know the correct way to transfer files read from mine GameDriver.java
to HashMap
.
As far as I know, one way to do this is to initialize Cop.java
like,
Cop N = new Cop();
and then make a method call
N.rescue();
What's the correct way to add read values? Can I use a solution like this? I am trying to get String cn
to save to map name
and int pts
save to points
below. Thanks for all the answers and please let me know if you need any clarification. I'll post my GameDriver.java
code as well as my Hero.java
code Thank you!
GameDriver.java
import java.io.*;
import java.util.*;
import java.awt.*;
public class GameDriver {
public static void main(String[] args) throws FileNotFoundException {
Cop N = new Cop();
String s;
File f = new File (args[0]);
Scanner input = new Scanner(f);
while (input.hasNext()) {
s = input.next();
if (s.equalsIgnoreCase("h")) { Character c1 = new Cop();
System.out.println(c1); }
if (s.equalsIgnoreCase("r")) { String cn = input.next(); //HashMap name
int pts = input.nextInt(); //HashMap points
N.rescue();}
}
}
}
Hero.java
import java.util.*;
import java.io.*;
import java.awt.*;
public abstract class Hero extends Character
{
private String heroname1;
public Hero() {
heroname1 = "Rick Grimes"; //the default player name
}
HashMap name = new HashMap<String, GameDriver>();
HashMap points = new HashMap<Integer, GameDriver>();
public Hero(String newhero) {
if (newhero.length() > 0) {
heroname1 = newhero;
} else { heroname1 = "Rick Grimes"; } //defaulted as protagonist
}
public String getHeroName() {
return heroname1; //return the name
}
public String rescue() { //class to rescue people or things
return heroname1 + " rescued " + name + " for " + points + "!";
}
public String toString() { //print
return heroname1;
}
}
common goal
I realize I didn't add to my overall goal: the goal is to read in a file to create a new hero (usually just one) and store multiple people / things in it in this hypothetical game. For example, if the file says
c h Rick Grimes //create hero
r Carl 100 //rescue for x amount of points
I want this data to be saved to a map or whatever and output like this:
Rick Grimes
Rick Grimes rescued Carl for 100 points!
also note that this should all be done via inheritance
source to share
No one has answered this question yet
See similar questions:
or similar: