Java - Collection - java

I'm working on my first java project and I have a question. The question should be quiet simple (though the the code is not that short, but there's no reason to be intimidated :) ). I create a basic roleplaying-game and I have an abstract class "Character" that defines each character. Among its subclasses you can find Mage, who has a Spellbook (Map). Spellbook class offers methods like addToSpellbook, that works fine. In addition I have an Inventory class that has addToInventory method, which is quit identical to addToSpellbook.
My question is as follows - why can I use In the main method addToSpellbook and can't use AddToInventory?
I guess the reason is that Map doesn't have AddToInventory, so I should override put, but still, how can I use addToSpellbook ?
public class Game {
public static void main(String[] args) throws IOException {
CharacterCreator heroCreator = new CharacterCreator();
CharacterCreator.showAllClasses();
Scanner sc = new Scanner(System.in);
int scan = sc.nextInt();
String chosenClass = CharacterCreator.getCharacterClass(scan);
Character hero = CharacterCreator.createCharacter(chosenClass);
try {
hero.displayCharacter();
}catch (Exception e){
System.out.println("Problem displaying character data");
}
hero.getInventory().addToInventory("Long sword");
CharacterCreator heroCreator2 = new CharacterCreator();
CharacterCreator.showAllClasses();
Scanner sc2 = new Scanner(System.in);
int scan2 = sc.nextInt();
String chosenClass2 = CharacterCreator.getCharacterClass(scan2);
Character hero2 = CharacterCreator.createCharacter(chosenClass2);
try {
hero2.displayCharacter();
}catch (Exception e){
System.out.println("Wrong input");
}
if(hero instanceof Mage) {
((Mage)hero).getSpellBook().addToSpellBook("Magic Missiles");
((Mage)hero).getSpellBook().addToSpellBook("Fireball");
((Mage)hero).getSpellBook().addToSpellBook("Mage Armor");
((Mage)hero).getSpellBook().showSpellBook();
((Mage)hero).getSpellBook().getSpellFromSpellbook("Fireball").castSpell(hero, hero2);
((Mage)hero).getSpellBook().getSpellFromSpellbook("Magic Missiles").castSpell(hero, hero2);
((Mage)hero).getSpellBook().getSpellFromSpellbook("Mage Armor").castSpell(hero, hero);
}
}
}
abstract public class Character {
private Equipment equipment;
private Map<String, Integer> inventory;
protected Character(String name){
equipment = new Equipment();
inventory = new HashMap<String, Integer>();
}
protected Character(String name, int lvl){
equipment = new Equipment();
inventory = new HashMap<String, Integer>();
}
}
public Equipment getEquipment() { return equipment; }
public Map getInventory() { return inventory; }
}
public class Inventory {
private Map<String,Integer> inventory;
Inventory() {
inventory = new HashMap<String, Integer>();
}
public void addToInventory(String item) {
boolean found = false;
try {
for (Iterator<Map.Entry<String, Integer>> iter = inventory.entrySet().iterator(); iter.hasNext(); ) {
Map.Entry<String, Integer> newItem = iter.next();
if (newItem.getKey() == item) {
inventory.put(item, inventory.get(newItem) + 1);
break;
}
}
}catch (Exception e) {
System.out.println(item + " : adding failed");
}
if (!found) {
inventory.put(item,1);
}
}
public void showInventory() {
System.out.println("Show Inventory: ");
for (Map.Entry<String,Integer> entry: inventory.entrySet()) {
System.out.println( entry.getKey() + ", quantity: " + entry.getValue() );
}
System.out.println("");
}
}
public class Mage extends Character {
private SpellBook spellBook;
public Mage(String name) {
super(name);
SpellBook spellbook = new SpellBook();
}
protected Mage(String name, int lvl){
super(name, lvl);
spellBook = new SpellBook();
}
public SpellBook getSpellBook() { return spellBook; }
}
}
public class SpellBook {
private Map<String, Spell> spellBook;
SpellBook() {
spellBook = new HashMap<String, Spell>();
}
public Map getSpellBook() { return spellBook; }
public void addToSpellBook(String spellName) {
Spell newSpell = null;
try {
if (DamageSpell.getSpell(spellName) != null) {
newSpell = DamageSpell.getSpell(spellName);
} else if (ChangeStatSpell.getSpell(spellName) != null) {
newSpell = ChangeStatSpell.getSpell(spellName);
}
System.out.println(newSpell.getSpellName() + " has been added to the spellbook");
spellBook.put(newSpell.getSpellName(), newSpell);
} catch (Exception e){
System.out.println("Adding " + spellName +"to spellbook has failed");
}
}
public void showSpellBook() {
System.out.println("Show spellbook: ");
for (Iterator<String> iter = spellBook.keySet().iterator(); iter.hasNext(); ) {
String spell = iter.next();
System.out.println(spell);
}
System.out.println("");
}
public Spell getSpellFromSpellbook(String spellName) {
Spell spl = null;
//Spell splGet = spellBook.get(spellName); /* straight forward implementation*/
// System.out.println("The spell " + splGet.getSpellName() + " has been retrived from the spellbook by using get method");
try {
for (Iterator<Map.Entry<String, Spell>> iter = spellBook.entrySet().iterator(); iter.hasNext(); ) {
Map.Entry<String, Spell> spell = iter.next();
if (spell.getKey() == spellName) {
spl = spell.getValue();
}
}
}catch (Exception e) {
System.out.println(spellName + " : no such spell in spellbook");
}
return spl;
}
}

getInventory() returns a Map and Map doesn't have the addToInventory() method.
getInventory() should add an Inventory instance.

Related

Java - write to a .csv file after sorting an arraylist of objects

I have an arraylist of object type:
public static ArrayList crimes = new ArrayList();
The CityCrime.java has the following:
public class CityCrime {
//Instance variables
private String city;
private String state;
private int population;
private int murder;
private int robbery;
private int assault;
private int burglary;
private int larceny;
private int motorTheft;
public int totalCrimes;
public static void main(String[] args) {
}
public int getTotalCrimes() {
return totalCrimes;
}
public void setTotalCrimes(int murder, int robbery, int assault, int burglary, int larceny, int motorTheft) {
this.totalCrimes = murder + robbery + assault + burglary + larceny + motorTheft;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
if(state.equalsIgnoreCase("ALABAMA")) {
this.state = "AL";
}
else if(state.equalsIgnoreCase("ALASKA")) {
this.state = "AK";
}
else if(state.equalsIgnoreCase("ARIZONA")) {
this.state = "AR";
}
//etc
}
public int getPopulation() {
return population;
}
public void setPopulation(int population) {
this.population = population;
}
public int getMurder() {
return murder;
}
public void setMurder(int murder) {
this.murder = murder;
}
public int getRobbery() {
return robbery;
}
public void setRobbery(int robbery) {
this.robbery = robbery;
}
public int getAssault() {
return assault;
}
public void setAssault(int assault) {
this.assault = assault;
}
public int getBurglary() {
return burglary;
}
public void setBurglary(int burglary) {
this.burglary = burglary;
}
public int getLarceny() {
return larceny;
}
public void setLarceny(int larceny) {
this.larceny = larceny;
}
public int getMotorTheft() {
return motorTheft;
}
public void setMotorTheft(int motorTheft) {
this.motorTheft = motorTheft;
}
public static void showAllMurderDetails() {
for (CityCrime crime : StartApp.crimes) {
System.out.println("Crime: City= " + crime.getCity() + ", Murder= " + crime.getMurder());
}
System.out.println();
}
public static int showAllViolentCrimes() {
int total = 0;
for(CityCrime crime : StartApp.crimes) {
total=total+crime.getMurder();
total=total+crime.getRobbery();
total=total+crime.getAssault();
}
System.out.println("Total of violent crimes: " + total);
return total;
}
public static int getPossessionCrimes() {
int total=0;
for (CityCrime crime : StartApp.crimes) {
total = total + crime.getBurglary();
total = total + crime.getLarceny();
total = total + crime.getMotorTheft();
}
System.out.println("Total of possession crimes: " + total);
return total;
}
}
The CityCrime ArrayList gets popular from another csv file:
public static void readCrimeData() {
File file = new File("crimeUSA.csv");
FileReader fileReader;
BufferedReader bufferedReader;
String crimeInfo;
String[] stats;
try {
fileReader = new FileReader(file);
bufferedReader = new BufferedReader(fileReader);
crimeInfo = bufferedReader.readLine();
crimeInfo = bufferedReader.readLine();
do {
CityCrime crime = new CityCrime(); // Default constructor
stats = crimeInfo.split(",");
{
if (stats[0] != null) {
crime.setCity(stats[0]);
}
if (stats[1] != null) {
crime.setState(stats[1]);
}
if (stats[2] != null) {
if (Integer.parseInt(stats[2]) >= 0) {
crime.setPopulation(Integer.parseInt(stats[2]));
}
}
if (stats[3] != null) {
if (Integer.parseInt(stats[3]) >= 0) {
crime.setMurder(Integer.parseInt(stats[3]));
}
}
if (stats[4] != null) {
if (Integer.parseInt(stats[4]) >= 0) {
crime.setRobbery(Integer.parseInt(stats[4]));
}
}
if (stats[5] != null) {
if (Integer.parseInt(stats[5]) >= 0) {
crime.setAssault(Integer.parseInt(stats[5]));
}
}
if (stats[6] != null) {
if (Integer.parseInt(stats[6]) >= 0) {
crime.setBurglary(Integer.parseInt(stats[6]));
}
}
if (stats[7] != null) {
if (Integer.parseInt(stats[7]) >= 0) {
crime.setLarceny(Integer.parseInt(stats[7]));
}
}
if (stats[8] != null) {
if (Integer.parseInt(stats[8]) >= 0) {
crime.setMotorTheft(Integer.parseInt(stats[8]));
}
}
crime.setTotalCrimes(Integer.parseInt(stats[3]), Integer.parseInt(stats[4]), Integer.parseInt(stats[5]), Integer.parseInt(stats[6]), Integer.parseInt(stats[7]), Integer.parseInt(stats[8]));
}
crimes.add(crime);
System.out.println(crime);
crimeInfo = bufferedReader.readLine();
} while (crimeInfo != null);
fileReader.close();
bufferedReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
I want to sort the array list and output to the csv file the list of robberies in descending order with the corresponding city. So far I have got the following, but I am stuck and not sure if going in the right direction. I'm relatively new to Java as you can probably tell so would appreciate it in as simple terms as can be:
public static void writeToFile() throws IOException {
File csvFile = new File("Robbery.csv");
FileWriter fileWriter = new FileWriter(csvFile);
ArrayList<Integer> robberyRates = new ArrayList();
for(CityCrime crime : crimes) {
robberyRates.add(crime.getRobbery());
}
Collections.sort(robberyRates);
}
The desired output will be for example:
Robbery,City
23511,New York
15863,Chicago
14353,Los Angeles
11371,Houston
10971,Philadelphia
etc…
Your help is appreciated. I have searched any page I can find on Google, but all I see from other example is writing to the csv from a set String ArrayList where they know the number of lines etc. Thankyou
You can try something like this:
public static void writeToFile() throws IOException {
File csvFile = new File("Robbery.csv");
try(FileWriter fileWriter = new FileWriter(csvFile)) { // try-with-resources to be sure that fileWriter will be closed at end
StringBuilder stringBuilder = new StringBuilder(); // Betther than String for multiple concatenation
crimes.sort(Comparator.comparingInt(CityCrime::getRobbery).reversed()); // I want to compare according to getRobbery, as Int, in reversed order
stringBuilder.append("Robbery")
.append(',')
.append("City")
.append(System.lineSeparator()); // To get new line character according to OS
for (final var crime : crimes)
stringBuilder.append(crime.getRobbery())
.append(',')
.append(crime.getCity())
.append(System.lineSeparator());
fileWriter.write(stringBuilder.toString());
}
}
If you are stuck because you can't figure out how to write a list, convert your list into a String and print the String instead.
I commented the piece of code, if you have any questions, don't hesitate.
Another solution is to use specific CSV parser library, OpenCSV for example.
It makes it easier to read and write CSV file.
Here a tutorial about OpenCSV:
https://mkyong.com/java/how-to-read-and-parse-csv-file-in-java/

Printing textdata from toString - Java

I am working on a personal Java project and learning how to print out data from a text file. My code (as you can see below) prints out the userNameGenerator and personName data perfectly fine but I want it to be printed out from the toString in my Java Class. How can I change my code to print it out from there?
This is how my toString looks like:
#Override
public String toString() {
return userNameGenerator + " -> " + "[" + personName + "]" ;
}
Full code:
import java.util.*;
import java.io.*;
public class Codes {
public static void main(String[] args) {
List<Codes2> personFile = new ArrayList<>();
try {
BufferedReader br = new BufferedReader(new FileReader("person-data.txt"));
String fileRead = br.readLine();
while (fileRead != null) {
String[] personData = fileRead.split(":");
String personName = personData[0];
String userNameGenerator = personData[1];
Codes2 personObj = new Codes2(personName, userNameGenerator);
personFile.add(personObj);
fileRead = br.readLine();
}
br.close();
}
catch (FileNotFoundException ex) {
System.out.println("File not found!");
}
catch (IOException ex) {
System.out.println("An error has occured: " + ex.getMessage());
}
Set<String> newStrSet = new HashSet<>();
for(int i = 0; i < personFile.size(); i++){
String[] regionSplit = personFile.get(i).getUserNameGenerator().split(", ");
for(int j = 0; j < regionSplit.length; j++){
newStrSet.add(regionSplit[j]);
}
}
for (String p: newStrSet) {
System.out.printf("%s -> ", p);
for (Codes2 s: personFile) {
if (s.getUserNameGenerator().contains(p)) {
System.out.printf("%s, ", s.getPersonName());
}
}
System.out.println();
}
}
}
Java Class:
public class Codes2 implements Comparable<Codes2> {
private String personName;
private String userNameGenerator;
public Codes2(String personName, String userNameGenerator) {
this.personName = personName;
this.userNameGenerator = userNameGenerator;
}
public String getPersonName() {
return personName;
}
public String getUserNameGenerator() {
return userNameGenerator;
}
#Override
public int compareTo(Codes2 o) {
return getUserNameGenerator().compareTo(o.getUserNameGenerator());
}
public int compare(Object lOCR1, Object lOCR2) {
return ((Codes2)lOCR1).userNameGenerator
.compareTo(((Codes2)lOCR2).userNameGenerator);
}
#Override
public String toString() {
return userNameGenerator + " -> " + "[" + personName + "]" ;
}
}
Everything looks right in your code.
I think you should just call the method when you are trying to print it out:
for (Codes2 s: personFile) {
if (s.getUserNameGenerator().contains(p)) {
System.out.printf("%s, ", s.toString());
}
}
This follows the fact that the class that prints out the object is not so closely coupled with the class that hold the data.
Try:
#Override
public String toString() {
return String.format("%s -> [%s]",this.userNameGenerator,this.personName);
}

Another serialization issue

I'm stuck trying to deserialize a list of Scores. I spent my entire day searching here but couldn't find a solution.. My code looks something like this:
public class Score implements Comparable<Score>, Serializable {
private String name;
private int score;
// .......
}
public class MySortedList<T> extends...implements...,Serializable {
private ArrayList<T> list;
// ....
}
public class ScoreManager {
private final String FILEPATH;
private final String FILENAME = "highscores.ser";
private MySortedList<Score> scoreList;
public ScoreManager() {
File workingFolder = new File("src\\games\\serialized");
if (!workingFolder.exists()) {
workingFolder.mkdir();
}
FILEPATH = workingFolder.getAbsolutePath();
if ((scoreList = loadScores()) == null) {
scoreList = new MySortedList<Score>();
}
}
public void addScore(Score score) {
scoreList.add(score);
saveScores();
}
public MySortedList<Score> getScoreList() {
return scoreList;
}
private void saveScores() {
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(new File(FILEPATH, FILENAME)))) {
out.writeObject(scoreList);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
#SuppressWarnings("unchecked")
private MySortedList<Score> loadScores() {
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(new File(FILEPATH, FILENAME)))) {
return (MySortedList<Score>) in.readObject();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
The loadScores() method returns just an empty MySortedList everytime.
However program succesfully creates the highscores.ser file in the correct place and I have absolutely no errors. Score objects are added correctly to the MySortedList object.
Any ideas? Perhaps worth mentioning that this is a part of a bigger program made in Swing. the methods in the ScoreManager class is called when the player dies
only if it can help, this code is working for me:
class Score implements Comparable<Score>, Serializable{
private int point;
public Score(int point) {
this.point = point;
}
public int getPoint(){
return point;
}
#Override
public int compareTo(Score o) {
if (o.getPoint() == this.getPoint())
return 0;
return this.point < o.getPoint() ? - 1 : 1;
}
public String toString() {
return "points: " + point;
}
}
class MyList<T> implements Serializable {
private ArrayList<T> list = new ArrayList<>();
public void add(T e){
list.add(e);
}
public void show() {
System.out.println(list);
}
}
public class Main {
File workingFolder;
String FILEPATH;
private final String FILENAME = "highscores.ser";
MyList<Score> list = new MyList<>();
public static void main(String[] args) {
Main main = new Main();
main.createFolder();
main.addItems();
main.saveScores();
MyList<Score> tempList = main.loadScores();
tempList.show();
main.addMoreItems();
main.saveScores();
tempList = main.loadScores();
tempList.show();
}
private void addItems() {
Score sc = new Score(10);
list.add(sc);
}
private void addMoreItems() {
Score sc1 = new Score(20);
list.add(sc1);
Score sc2 = new Score(30);
list.add(sc2);
}
private void createFolder() {
workingFolder = new File("src\\games\\serialized");
if (!workingFolder.exists()) {
workingFolder.mkdir();
}
FILEPATH = workingFolder.getAbsolutePath();
}
private void saveScores() {
System.out.println("before save: " + list);
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(new File(FILEPATH, FILENAME)))) {
out.writeObject(list);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
#SuppressWarnings("unchecked")
private MyList<Score> loadScores() {
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(new File(FILEPATH, FILENAME)))) {
return (MyList<Score>) in.readObject();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}

Java Cannot instantiate the type Module (Not Abstract Class)

I'm having issues compiling my code. eclipse gives me this error code:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Cannot instantiate the type Module
Cannot instantiate the type Module
at Model.AddModule(Model.java:214)
at Model.loadFromTextFiles(Model.java:129)
at Model.menu(Model.java:98)
at Run.main(Run.java:7)
Here's my model code :
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.*;
import java.util.*;
import com.sun.xml.internal.ws.api.server.Module;
public class Model implements java.io.Serializable {
private Student[] StudentList = new Student[0];
private Module[] ModuleList = new Module[0];
public void runTests() throws FileNotFoundException {
Scanner scan=new Scanner (System.in);
System.out.println("Loading From text files");
scan.nextLine();
loadFromTextFiles();
printReport();
System.out.println("Saving serializable");
scan.nextLine();
saveSer();
System.out.println("Creating a new module(CS12330)");
scan.nextLine();
String[] temp=new String[0];
AddModule("CS12330",temp);
printReport();
System.out.println("Loading from serialixed file");
scan.nextLine();
loadSer();
printReport();
System.out.println("Saving using XML");
scan.nextLine();
saveXML();
System.out.println("Creating a new module(CS15560)");
scan.nextLine();
AddModule("CS15560",temp);
printReport();
System.out.println("Loading from XML file");
scan.nextLine();
loadXML();
printReport();
}
public void menu() throws FileNotFoundException {
while (true) {
System.out.println("Menu");
System.out.println("1-Run Tests");
System.out.println("2-Add Student");
System.out.println("4-Add Module");
System.out.println("5-Add A Student To Module");
System.out.println("6-Save (Text File)");
System.out.println("7-Save (Serialization)");
System.out.println("8-Save (XML)");
System.out.println("9-Load (Text File)");
System.out.println("10-Load (Serialization)");
System.out.println("11-Load (XML)");
Scanner scan=new Scanner (System.in);
String response=scan.nextLine();
if (response.equals("1")){
runTests();
} else if (response.equals("2")) {
System.out.print("Enter UID: ");
String UID=scan.nextLine();
System.out.print("Enter Surname: ");
String surname=scan.nextLine();
System.out.print("Enter First Name: ");
String firstname=scan.nextLine();
System.out.print("Course Code: ");
String courseCode=scan.nextLine();
AddStudent(UID,surname,firstname,courseCode);
} else if (response.equals("4")) {
System.out.print("Enter Module Code: ");
String moduleCode=scan.nextLine();
String[] temp=new String[0];
AddModule(moduleCode,temp);
} else if (response.equals("5")) {
System.out.print("Enter Module Code: ");
String moduleCode=scan.nextLine();
Module m=findAModule(moduleCode);
scan.nextLine();
if(m!=null){
System.out.print("Enter UID: ");
String UID=scan.nextLine();
Student s=findAStudent(UID);
if (s!=null) {
//m.addThisStudent(s);
}else System.out.println("Student Not Found");
}else System.out.println("Module Not Found");
} else if (response.equals("6")) {
saveToTextFiles();
} else if (response.equals("7")) {
saveSer();
} else if (response.equals("8")) {
saveXML();
} else if (response.equals("9")) {
loadFromTextFiles();
} else if (response.equals("10")) {
loadSer();
} else if (response.equals("11")) {
loadXML();
}
}
}
public void loadFromTextFiles() throws FileNotFoundException {
Scanner infile=new Scanner(new InputStreamReader(new FileInputStream("students.txt")));
int num=infile.nextInt();infile.nextLine();
for (int i=0;i<num;i++) {
String u=infile.nextLine();
String sn=infile.nextLine();
String fn=infile.nextLine();
String c=infile.nextLine();
AddStudent(u,sn,fn,c);
}
infile.close();
infile=new Scanner(new InputStreamReader(new FileInputStream("modules.txt")));
num=infile.nextInt();infile.nextLine();
for (int i=0;i<num;i++) {
String c=infile.nextLine();
int numOfStudents=infile.nextInt();infile.nextLine();
String[] students = new String[numOfStudents];
for (int j=0;j<numOfStudents;j++) {
students[j] = infile.nextLine();
}
AddModule(c,students);
}
infile.close();
}
public void saveToTextFiles() {
try {
PrintWriter outfile = new PrintWriter(new OutputStreamWriter (new FileOutputStream("Students.txt")));
outfile.println(StudentList.length);
for(int i=0;i<StudentList.length;i++) {
outfile.println(StudentList[i].getUID());
outfile.println(StudentList[i].getSName());
outfile.println(StudentList[i].getFName());
outfile.println(StudentList[i].getDegree());
}
outfile.close();
outfile = new PrintWriter(new OutputStreamWriter (new FileOutputStream("Modules.txt")));
outfile.println(ModuleList.length);
for(int i=0;i<ModuleList.length;i++) {
outfile.println(ModuleList[i].getCode());
outfile.println(ModuleList[i].getStudents().length);
for (int j=0;j<(ModuleList[i]).getStudents().length;j++) {
outfile.println(ModuleList[i].getStudents()[j]);
}
}
outfile.close();
}
catch(IOException e) {
}
}
public void loadSer() {
Model m =null;
try{
FileInputStream fileIn = new FileInputStream("Model.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
m=(Model) in.readObject();
in.close();
fileIn.close();
}catch (Exception e){}
if (m!=null) {
setStudentList(m.getStudentList());
setModuleList(m.getModuleList());
}
}
public void saveSer() {
try {
FileOutputStream fileOut = new FileOutputStream("Model.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(this);
out.close();
fileOut.close();
} catch(IOException e) {}
}
public void loadXML() {
try {
Model m = null;
XMLDecoder decoder = new XMLDecoder (new BufferedInputStream (new FileInputStream("model.xml")));
m = (Model) decoder.readObject();
decoder.close();
setStudentList(m.getStudentList());
setModuleList(m.getModuleList());
} catch (IOException e) {
e.printStackTrace();
}
}
public void saveXML() {
try {
Model m = null;
XMLEncoder encoder = new XMLEncoder (new BufferedOutputStream (new FileOutputStream("model.xml")));
encoder.writeObject(this);
encoder.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void AddModule(String c, String[] students) {
int length = ModuleList.length;
Module NewArray[]=new Module[length+1];
for (int i=0;i<length+1;i++) {
if (i<length) {
NewArray[i]=new Module(ModuleList[i]);
}
}
NewArray[length]=new Module(c, students);
ModuleList = NewArray.clone();
}
private void AddStudent(String u, String sn, String fn, String c) {
int length = StudentList.length;
Student NewArray[]=new Student[StudentList.length+1];
for (int i=0;i<StudentList.length+1;i++) {
if (i<length) {
NewArray[i]=new Student(StudentList[i]);
}
}
NewArray[length]=new Student(u,sn,fn,c);
StudentList = NewArray.clone();
}
public void printReport() {
for (int i= 0;i<ModuleList.length;i++) {
System.out.println(ModuleList[i].toString(this));
}
}
public Student findAStudent(String UID) {
for(int i=0;i<StudentList.length;i++) {
if (StudentList[i].getUID().compareTo(UID)==0) {
return StudentList[i];
}
}
return null;
}
public Module findAModule(String moduleCode) {
for(int i=0;i<ModuleList.length;i++) {
if (ModuleList[i].getCode().compareTo(moduleCode)==0) {
return ModuleList[i];
}
}
return null;
}
public Module[] getModuleList() {
return ModuleList;
}
public Student[] getStudentList() {
return StudentList;
}
public void setModuleList(Module[] m) {
ModuleList=m.clone();
}
public void setStudentList(Student[] s) {
StudentList=s.clone();
}
}
And here's my module code:
public class Module{
private String Code;
private String[] students = new String[0];
public Module (){};
public Module(String c, String[] s) {
Code=c;
students=s;
}
public Module(Module module) {
Code=module.getCode();
students=module.getStudents();
}
public String[] getStudents() {
return students;
}
public String getCode() {
return Code;
}
public void addThisStudent(Student s) {
AddStudent(s.getUID());
}
public String toString(Model mod) {
String studentString ="";
if (students.length == 0) {
studentString = "\n No Students";
}else {
for (int i=0;i<students.length;i++) {
Student s = mod.findAStudent(students[i]);
if (s!=null) {
studentString += "\n "+s.toString();
}
}
}
return Code + studentString;
}
private void AddStudent(String UIDToAdd) {
int length = students.length;
String NewArray[]=new String[students.length+1];
for (int i=0;i<length;i++) {
NewArray[i] = students[i];
}
NewArray[length] = UIDToAdd;
students = NewArray.clone();
}
}
I honestly have no idea why this is happening. I've googled my error before and I only found issues that involved abstract classes.
You are importing the wrong Module - you are importing:
import com.sun.xml.internal.ws.api.server.Module;
You need to import your own Module.
That's because your imported "com.sun.xml.internal.ws.api.server.Module" in your Model class. Try taking that out and importing your.package.Module instead.

JavaAdding List to TreeMap and Display out key and list

I have the following textfile contains the information that will be added to the treemap.
1 apple
1 orange
3 pear
3 pineapple
4 dragonfruit
my code:
public class Treemap {
private List<String> fList = new ArrayList<String>();
private TreeMap<Integer, List<String>> tMap = new TreeMap<Integer, List<String>>();
public static void main(String[] args) {
Treemap tm = new Treemap();
String file = "";
if (args.length == 1) {
file = args[0];
try {
tm.Read(file);
} catch (IOException ex) {
System.out.println("Error");
}
} else {
System.out.println("Usage: java treemap 'Filename'");
System.exit(1);
}
}
public void Read(String file) throws IOException {
//Scanner in = null;
BufferedReader in = null;
InputStream fis;
try {
fis = new FileInputStream(file);
in = new BufferedReader(new InputStreamReader(fis));
String line = null;
while ((line = in.readLine()) != null) {
String[] file_Array = line.split(" ", 2);
if (file_Array[0].equalsIgnoreCase("1")) {
Add(Integer.parseInt(file_Array[0]), file_Array[1]);
Display(1);
} else if (file_Array[0].equalsIgnoreCase("3")) {
Add(Integer.parseInt(file_Array[0]), file_Array[1]);
Display(3);
} else if (file_Array[0].equalsIgnoreCase("4")) {
Add(Integer.parseInt(file_Array[0]), file_Array[1]);
Display(4);
}
}
} catch (IOException ex) {
System.out.println("Input file " + file + " not found");
System.exit(1);
} finally {
in.close();
}
}
public void Add(int item, String fruit) {
if (tMap.containsKey(item) == false) {
tMap.put(item, fList);
fList.add(fruit);
System.out.println("Fruits added " + item);
} else {
System.out.println("not exist");
}
}
public void Display(int item) {
if (tMap.containsKey(item)) {
System.out.print("Number " + item + ":" + "\n");
System.out.print(fList);
System.out.print("\n");
} else {
System.out.print(item + " WAS NOT FOUND"+ "\n");
}
}
}
ideal output
Number 1:
[apple, orange]
Number 3:
[pear, pineapple]
Number 4:
[dragonfruit]
currently i only able to output this
Fruits added 1
Number 1:
[apple]
not exist
Number 1:
[apple]
Fruits added 3
Number 3:
[apple, pear]
not exist
Number 3:
[apple, pear]
Fruits added 4
Number 4:
[apple, pear, dragonfruit]
How should I display the item following by the list of fruit added to that number?
Try this code. Its working. By the way you should improve this code. The code is not optimised.
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;
public class Treemap {
private List<String> fList = new ArrayList<String>();
private TreeMap<Integer, List<String>> tMap = new TreeMap<Integer, List<String>>();
public static void main(String[] args) {
Treemap tm = new Treemap();
String file = "";
if (args.length == 1) {
file = args[0];
try {
tm.Read(file);
} catch (IOException ex) {
System.out.println("Error");
}
} else {
System.out.println("Usage: java treemap 'Filename'");
System.exit(1);
}
}
public void Read(String file) throws IOException {
//Scanner in = null;
BufferedReader in = null;
InputStream fis;
try {
fis = new FileInputStream(file);
in = new BufferedReader(new InputStreamReader(fis));
String line = null;
while ((line = in.readLine()) != null) {
String[] file_Array = line.split(" ", 2);
if (file_Array[0].equalsIgnoreCase("1")) {
Add(Integer.parseInt(file_Array[0]), file_Array[1]);
// Display(1);
} else if (file_Array[0].equalsIgnoreCase("3")) {
Add(Integer.parseInt(file_Array[0]), file_Array[1]);
// Display(3);
} else if (file_Array[0].equalsIgnoreCase("4")) {
Add(Integer.parseInt(file_Array[0]), file_Array[1]);
// Display(4);
}
}
} catch (IOException ex) {
System.out.println("Input file " + file + " not found");
System.exit(1);
} finally {
for(int i: tMap.keySet())
Display(i);
in.close();
}
}
public void Add(int item, String fruit) {
if (tMap.containsKey(item) == false) {
fList = new ArrayList<>();
fList.add(fruit);
tMap.put(item, fList);
// System.out.println("Fruits added " + item);
} else {
tMap.get(item).add(fruit);
// System.out.println("not exist");
}
}
public void Display(int item) {
if (tMap.containsKey(item)) {
System.out.print("Number " + item + ":" + "\n");
System.out.print(tMap.get(item));
System.out.print("\n");
} else {
System.out.print(item + " WAS NOT FOUND"+ "\n");
}
}
}
Here is your READ , ADD ad DISPLAY method,
public void Read(String file) throws IOException {
BufferedReader in = null;
InputStream fis;
try {
fis = new FileInputStream(file);
in = new BufferedReader(new InputStreamReader(fis));
String line = null;
while ((line = in.readLine()) != null) {
String[] file_Array = line.split(" ", 2);
Add(Integer.parseInt(file_Array[0]),file_Array[1]);
}
Display(-1); // -1 for displaying all
} catch (IOException ex) {
System.out.println("Input file " + file + " not found");
System.exit(1);
} finally {
in.close();
}
}
public void Add(int item, String fruit) {
if (tMap.containsKey(item)) {
fList = tMap.get(item);
} else {
fList = new ArrayList<String>();
}
fList.add(fruit);
tMap.put(item, fList);
}
public void Display(int key) {
if(key == -1){
for (Map.Entry<Integer, List<String>> entry : tMap.entrySet()) {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
}else{
System.out.println(key);
System.out.println(tMap.get(key));
}
}
You make unnecessary complicated your code. Try with simple code.
public class Treemap {
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(new File("file.txt"));
Map<Integer, List<String>> tMap = new TreeMap<>();
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] values=line.split(" ");
List<String> fList;
Integer key=Integer.valueOf(values[0]);
if(tMap.containsKey(key)){//Key already inserted
fList=tMap.get(key); //Get existing List of key
fList.add(values[1]);
}
else{
fList = new ArrayList<String>();
fList.add(values[1]);
tMap.put(key, fList);
}
}
for (Map.Entry<Integer, List<String>> entry : tMap.entrySet()) {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
}
}
Output:
1
[apple, orange]
3
[pear, pineapple]
4
[dragonfruit]
Change some code for the method Add(), which is incorrect in your code.
What if the Map contains the key?
Following code is modified based on your code, hope this can help you some.
public void Add(int item, String fruit) {
if (tMap.containsKey(item)==false) {
fList.clear();
fList.add(fruit);
tMap.put(item, fList);
System.out.println("Fruits added " + item);
} else {
tMap.get(item).add(fruit);
}
}

Categories

Resources