Issue loading data from csv file - Java - java

As it stands I have a data set in the form of a .csv file which you can find here. Also there is some brief documentation on it which you can find here. What I am attempting to do is to manipulate the data set so that I can work with some machine learning algorithms but as it stands I can't seem to print the outputted data to the console
ImageMatrix.java
import java.util.Arrays;
public class ImageMatrix {
public static int[] data;
public int classCode;
public ImageMatrix(int[] data, int classCode) {
assert data.length == 64;
}
public String toString() {
return "Class Code: " + classCode + " DataSet:" + Arrays.toString(data) + "\n";
}
public int[] getData() {
return data;
}
public int getClassCode() {
return classCode;
}
}
ImageMatrixDB.java
import java.io.*;
import java.util.*;
public class ImageMatrixDB implements Iterable<ImageMatrix> {
List<ImageMatrix> list = new ArrayList<ImageMatrix>();
public static ImageMatrixDB load(String f) throws IOException {
ImageMatrixDB result = new ImageMatrixDB();
try (FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr)) {
for (String line; null != (line = br.readLine()); ) {
int lastComma = line.lastIndexOf(',');
int classCode = Integer.parseInt(line.substring(1 + lastComma));
int[] data = Arrays.stream(line.substring(0, lastComma).split(","))
.mapToInt(Integer::parseInt)
.toArray();
result.list.add(new ImageMatrix(data, classCode));
}
System.out.println(ImageMatrix.data.toString());
}
return result;
}
public Iterator<ImageMatrix> iterator() {
return this.list.iterator();
}
public static void main(String[] args){
ImageMatrixDB i = new ImageMatrixDB();
i.load("dataset1.csv"); // <<< ERROR IS HERE
}
}
The error is within my main function on the line i.load(... I know I must be missing something or have made a mistake somewhere, I have tried altering the data from static but it just throws more errors and I can't figure it out. Any ideas?

Your issue is in the ImageMatrix class.
You never set the int[] data in the constructor. You have:
public ImageMatrix(int[] data, int classCode) {
assert data.length == 64;
}
You need:
public ImageMatrix(int[] data, int classCode) {
assert data.length == 64;
this.data = data;
this.classCode = classCode;
}
Here is your updated/complete/working code:
ImageMatrix:
import java.util.*;
public class ImageMatrix {
private int[] data;
private int classCode;
public ImageMatrix(int[] data, int classCode) {
assert data.length == 64;
this.data = data;
this.classCode = classCode;
}
public String toString() {
return "Class Code: " + classCode + " DataSet:" + Arrays.toString(data) + "\n";
}
public int[] getData() {
return data;
}
public int getClassCode() {
return classCode;
}
}
ImageMatrixDB:
import java.util.*;
import java.io.*;
public class ImageMatrixDB implements Iterable<ImageMatrix> {
private List<ImageMatrix> list = new ArrayList<ImageMatrix>();
public ImageMatrixDB load(String f) throws IOException {
try (
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr)) {
String line = null;
while((line = br.readLine()) != null) {
int lastComma = line.lastIndexOf(',');
int classCode = Integer.parseInt(line.substring(1 + lastComma));
int[] data = Arrays.stream(line.substring(0, lastComma).split(","))
.mapToInt(Integer::parseInt)
.toArray();
ImageMatrix matrix = new ImageMatrix(data, classCode);
list.add(matrix);
}
}
return this;
}
public void printResults(){
for(ImageMatrix matrix: list){
System.out.println(matrix);
}
}
public Iterator<ImageMatrix> iterator() {
return this.list.iterator();
}
public static void main(String[] args){
ImageMatrixDB i = new ImageMatrixDB();
try{
i.load("cw2DataSet1.csv");
i.printResults();
}
catch(Exception ex){
ex.printStackTrace();
}
}
}

Your load method can throw an IOException. You need to catch it in order to successfully compile
public static void main(String[] args){
ImageMatrixDB i = new ImageMatrixDB();
try{
i.load("dataset1.csv"); // <<< ERROR IS HERE
}
catch(Exception e){
System.out.println(e.getMessage());
}
}

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/

How to store an ArrayList in a file?

I have a class which represents an ArrayList stored in a file, because I need an ArrayList with multiple gigabytes of data in it which is obviously too large to be stored in memory. The data is represented by a class called Field and the function Field.parse() is just for converting the Field into a String and the other way.
The Field class stores a list of (strange) chess pieces and their coordinates.
My class is working fine, but it takes a long time to add an element to the file and I need my program to run as fast as possible. Does anyone know a more efficient/faster way of doing things?
Also, I am not allowed to use external libraries/apis. Please keep that in mind.
This is the class which is responsible for storing Field objects in a temp file:
private File file;
private BufferedReader reader;
private BufferedWriter writer;
public FieldSaver() {
try {
file = File.createTempFile("chess-moves-", ".temp");
System.out.println(file.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
}
public void add(Field field) {
try {
File temp = File.createTempFile("chess-moves-", ".temp");
writer = new BufferedWriter(new FileWriter(temp));
reader = new BufferedReader(new FileReader(file));
String line;
while((line = reader.readLine()) != null ) {
writer.write(line);
writer.newLine();
}
reader.close();
writer.write(field.parse());
writer.close();
file.delete();
file = new File(temp.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
}
public Field get(int n) {
try {
reader = new BufferedReader(new FileReader(file));
for (int i = 0; i < n; i++) {
reader.readLine();
}
String line = reader.readLine();
reader.close();
return Field.parse(line);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
And this is the Field class:
private WildBoar wildBoar;
private HuntingDog[] huntingDogs;
private Hunter hunter;
private int size;
#Override
public String toString() {
String result = "Wildschwein: " + wildBoar.toString();
for (HuntingDog dog : huntingDogs) {
result += "; Hund: " + dog.toString();
}
return result + "; Jäger: " + hunter.toString();
}
#Override
public boolean equals(Object obj) {
if (obj instanceof Field) {
Field field = (Field) obj;
HuntingDog[] dogs = field.getHuntingDogs();
return wildBoar.equals(field.getWildBoar()) && hunter.equals(field.getHunter()) && huntingDogs[0].equals(dogs[0]) && huntingDogs[1].equals(dogs[1]) && huntingDogs[2].equals(dogs[2]);
}
return false;
}
public Field(int size, WildBoar wildBoar, HuntingDog[] huntingDogs, Hunter hunter) {
this.size = size;
this.wildBoar = wildBoar;
this.huntingDogs = huntingDogs;
this.hunter = hunter;
}
public WildBoar getWildBoar() {
return wildBoar;
}
public HuntingDog[] getHuntingDogs() {
return huntingDogs;
}
public Hunter getHunter() {
return hunter;
}
public int getSize() {
return size;
}
public static Field parse(String s) {
String[] arr = s.split(",");
WildBoar boar = WildBoar.parse(arr[0]);
Hunter hunter = Hunter.parse(arr[1]);
HuntingDog[] dogs = new HuntingDog[arr.length - 2];
for(int i = 2; i < arr.length; i++) {
dogs[i - 2] = HuntingDog.parse(arr[i]);
}
return new Field(8, boar, dogs, hunter);
}
public String parse() {
String result = wildBoar.parse() + "," + hunter.parse();
for(HuntingDog dog : huntingDogs) {
result += "," + dog.parse();
}
return result;
}
Here's an MCVE to do what you want, based on the information you provided.
You can run it and see that it can save a Field to the file and get a Field by index very quickly.
The Fields are constant length, so you can get a Field by index by going to byte offset of index times field length in bytes. This would be significantly more difficult if the field were not constant length.
import java.io.Closeable;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class FieldSaver implements Closeable {
public static void main(String[] args) throws IOException {
File f = File.createTempFile("chess-moves-", ".temp");
try (FieldSaver test = new FieldSaver(f);) {
for (byte i = 0; i < 100; i++) {
test.add(new Field(8, new WildBoar(i, i), new Hunter(i, i), new HuntingDog[] {
new HuntingDog(i, i),
new HuntingDog(i, i),
new HuntingDog(i, i) }));
}
// Get a few Fields by index
System.out.println(test.get(0));
System.out.println(test.get(50));
System.out.println(test.get(99));
// EOF exception, there is no Field 100
// System.out.println(test.get(100));
}
}
private final RandomAccessFile data;
public FieldSaver(File f) throws FileNotFoundException {
data = new RandomAccessFile(f, "rw");
}
public void add(Field field) throws IOException {
data.seek(data.length());
field.write(data);
}
public Field get(int index) throws IOException {
data.seek(index * Field.STORAGE_LENGTH_BYTES);
return Field.read(data);
}
public void close() throws IOException { data.close(); }
static abstract class Piece {
protected byte xPos;
protected byte yPos;
public Piece(DataInput data) throws IOException {
xPos = data.readByte();
yPos = data.readByte();
}
public Piece(byte xPos, byte yPos) {
this.xPos = xPos;
this.yPos = yPos;
}
public void write(DataOutput data) throws IOException {
data.writeByte(xPos);
data.writeByte(yPos);
}
public String toString() { return "[" + xPos + ", " + yPos + "]"; }
}
static class Hunter extends Piece {
public Hunter(byte xPos, byte yPos) { super(xPos, yPos); }
public Hunter(DataInput data) throws IOException { super(data); }
}
static class HuntingDog extends Piece {
public HuntingDog(byte xPos, byte yPos) { super(xPos, yPos); }
public HuntingDog(DataInput data) throws IOException { super(data); }
}
static class WildBoar extends Piece {
public WildBoar(byte xPos, byte yPos) { super(xPos, yPos); }
public WildBoar(DataInput data) throws IOException { super(data); }
}
static class Field {
// size of boar + hunter + 3 dogs
public static final int STORAGE_LENGTH_BYTES = 2 + 2 + (3 * 2);
private int size;
private WildBoar boar;
private Hunter hunter;
private final HuntingDog[] dogs;
public Field(int size, WildBoar wildBoar, Hunter hunter, HuntingDog[] huntingDogs) {
this.size = size;
this.boar = wildBoar;
this.hunter = hunter;
this.dogs = huntingDogs;
}
public String toString() {
String result = "Wildschwein: " + boar.toString();
for (HuntingDog dog : dogs) {
result += "; Hund: " + dog.toString();
}
return result + "; Jäger: " + hunter.toString();
}
public static Field read(DataInput data) throws IOException {
WildBoar boar = new WildBoar(data);
Hunter hunter = new Hunter(data);
HuntingDog[] dogs = new HuntingDog[3];
for (int i = 0; i < 3; i++) {
dogs[i] = new HuntingDog(data);
}
return new Field(8, boar, hunter, dogs);
}
public void write(DataOutput data) throws IOException {
boar.write(data);
hunter.write(data);
for (HuntingDog dog : dogs) {
dog.write(data);
}
}
}
}
Use a Map implementation like Cache from ehcache. This library will optimize for you so you don't have to handle writing and reading to disk and manage when to keep it in memory or on disk. You can just use it as a normal map. You probably want a map instead of a list for faster lookup so the library can optimize even more for you.
http://www.ehcache.org/
CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
.withCache("preConfigured",
CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
ResourcePoolsBuilder.heap(100))
.build())
.build(true);
Cache<Long, String> preConfigured
= cacheManager.getCache("preConfigured", Long.class, String.class);

Java: Save System Won't Work [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Well, I'm making a game and in my framework I created a save system. My save system works fine but for some reason, it does not seem to want to save my files! It gives me this error:
Chaos Blades: There was an error in creating the file!
Exception in thread "LWJGL Application" java.lang.NullPointerException
at cb.core.FileBuilder.writeString(FileBuilder.java:31)
at cb.player.PlayerStats.init(PlayerStats.java:46)
at cb.player.Player.init(Player.java:17)
at cb.entities.EntityManager.init(EntityManager.java:8)
at cb.core.Initialiser.init(Initialiser.java:11)
at cb.core.Main.create(Main.java:11)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:143)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:120)
Here's my FileBuilder class:
package cb.core;
import java.io.*;
import java.util.*;
public class FileBuilder {
private Formatter formatter;
public void openFile(String file) {
try {
formatter = new Formatter(file);
} catch(Exception e) {
System.err.println("Chaos Blades: There was an error in creating the file!");
}
}
public void closeFile() {
formatter.close();
}
public void writeInteger(int i) {
formatter.format("%i \n", i);
}
public void writeFloat(float f) {
formatter.format("%f \n", f);
}
public void writeString(String s) {
formatter.format("%s \n", s);
}
public void appendInt(String file, int i) {
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file, true)))) {
out.println(i);
}catch (IOException e) {
System.err.println("Darkbyte: Couldn't find file!");
}
}
public void appendFloat(String file, float f) {
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file, true)))) {
out.println(f);
} catch (IOException e) {
System.err.println("Darkbyte: Couldn't find file!");
}
}
public void appendString(String file, String s) {
try(PrintWriter out = new PrintWriter(new BufferedWriter(newFileWriter(file, true)))) {
out.println(s);
}catch (IOException e) {
System.err.println("Darkbyte: Couldn't find file!");
}
}
}
Here's my PlayerStats class:
package cb.player;
import java.io.*;
import cb.core.*;
import cb.core.FileReader;
public class PlayerStats {
public enum Class {
WARRIOR, ARCHER, MAGE
}
private static int health, attack, defense, melee, ranged, magic, crafting;
private static int hxp, axp, dxp, mexp, rxp, mgxp, cxp;
private static Class pclass;
static void init() {
FileBuilder saver = new FileBuilder();
FileReader reader = new FileReader();
File statfile = new File("saves/stats.cbsave");
File xpfile = new File("saves/xp.cbsave");
if(statfile.exists()) {
reader.openFile("saves/stats.cbsave");
health = reader.setVariableToIntUsingFilePosition(1);
attack = reader.setVariableToIntUsingFilePosition(2);
defense = reader.setVariableToIntUsingFilePosition(3);
melee = reader.setVariableToIntUsingFilePosition(4);
ranged = reader.setVariableToIntUsingFilePosition(5);
magic = reader.setVariableToIntUsingFilePosition(6);
crafting = reader.setVariableToIntUsingFilePosition(7);
pclass.equals(reader.setVariableToStringUsingFilePosition(8));
reader.closeFile();
} else {
health = 1;
attack = 1;
defense = 1;
melee = 1;
ranged = 1;
magic = 1;
crafting = 1;
saver.openFile("saves/stats.cbsave");
saver.writeString("" + health);
saver.writeString("" + attack);
saver.writeString("" + defense);
saver.writeString("" + melee);
saver.writeString("" + ranged);
saver.writeString("" + magic);
saver.writeString("" + crafting);
saver.writeString(pclass.toString());
saver.closeFile();
}
if(xpfile.exists()) {
reader.openFile("saves/xp.cbsave");
hxp = reader.setVariableToIntUsingFilePosition(1);
axp = reader.setVariableToIntUsingFilePosition(2);
dxp = reader.setVariableToIntUsingFilePosition(3);
mexp = reader.setVariableToIntUsingFilePosition(4);
rxp = reader.setVariableToIntUsingFilePosition(5);
mgxp = reader.setVariableToIntUsingFilePosition(6);
cxp = reader.setVariableToIntUsingFilePosition(7);
reader.closeFile();
} else {
hxp = 0;
axp = 0;
dxp = 0;
mexp = 0;
rxp = 0;
mgxp = 0;
cxp = 0;
saver.openFile("saves/xp.cbsave");
saver.writeInteger(hxp);
saver.writeInteger(axp);
saver.writeInteger(dxp);
saver.writeInteger(mexp);
saver.writeInteger(rxp);
saver.writeInteger(mgxp);
saver.writeInteger(cxp);
saver.closeFile();
}
}
static void dispose() {
FileBuilder saver = new FileBuilder();
saver.openFile("saves/stats.cbsave");
saver.writeInteger(health);
saver.writeInteger(attack);
saver.writeInteger(defense);
saver.writeInteger(melee);
saver.writeInteger(ranged);
saver.writeInteger(magic);
saver.writeInteger(crafting);
saver.writeString(pclass.toString());
saver.closeFile();
saver.openFile("saves/xp.cbsave");
saver.writeInteger(hxp);
saver.writeInteger(axp);
saver.writeInteger(dxp);
saver.writeInteger(mexp);
saver.writeInteger(rxp);
saver.writeInteger(mgxp);
saver.writeInteger(cxp);
saver.closeFile();
}
public static int getHealth() {
return health;
}
public static int getAttack() {
return attack;
}
public static int getDefense() {
return defense;
}
public static int getMelee() {
return melee;
}
public static int getRanged() {
return ranged;
}
public static int getMagic() {
return magic;
}
public static int getCrafting() {
return crafting;
}
public static int getHealthXP() {
return hxp;
}
public static int getAttackXP() {
return hxp;
}
public static int getDefenseXP() {
return hxp;
}
public static int getMeleeXP() {
return hxp;
}
public static int getRangedXP() {
return hxp;
}
public static int getMagicXP() {
return hxp;
}
public static int getCraftingXP() {
return hxp;
}
public static void setHealth(int health) {
PlayerStats.health = health;
}
public static void setAttack(int attack) {
PlayerStats.attack = attack;
}
public static void setDefense(int defense) {
PlayerStats.defense = defense;
}
public static void setMelee(int melee) {
PlayerStats.melee = melee;
}
public static void setRanged(int ranged) {
PlayerStats.ranged = ranged;
}
public static void setMagic(int magic) {
PlayerStats.magic = magic;
}
public static void setCrafting(int crafting) {
PlayerStats.crafting = crafting;
}
}
I'm not sure what's wrong so help me out please!
openFile() is failing since the file does not exist or you can't write to it. Try explicitly creating the files if they do not exist:
File statfile = new File("saves/stats.cbsave");
if(statfile.exists()) {
...
} else {
statfile.createNewFile();
...
}

How can i return an array in java that is accessible by other objects?

I want to return an array that is accessible by other objects after having read a text file. My instruction parsing class is:
import java.io.*;
public class Instruction {
public String[] instructionList;
public String[] readFile() throws IOException {
FileInputStream in = new FileInputStream("directions.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
int n = 5;
instructionList = new String[n];
for (int j = 0; j < instructionList.length; j++) {
instructionList[j] = br.readLine();
}
in.close();
return instructionList;
}
}
The above takes in a text file with 5 lines of text in it. In my main() I want to run that function and have the string array be accessible to other objects.
import java.util.Arrays;
public class RoverCommand {
public static void main(String[] args) throws Exception {
Instruction directions = new Instruction();
directions.readFile();
String[] directionsArray;
directionsArray = directions.returnsInstructionList();
System.out.println(Arrays.toString(directionsArray));
}
}
What's the best way to do that? I would need the elements of the array to be integers if they are numbers and strings if they are letters. P.S. I'm brand new to Java. is there a better way to do what I'm doing?
You don't have to use generics. I try to catch exceptions in the accessors and return null if anything blows up. So you can test if the value returned is null before proceeding.
// Client.java
import java.io.IOException;
public class Client {
public static void main(String args[]) {
try {
InstructionList il = new InstructionList();
il.readFile("C:\\testing\\ints.txt", 5);
int[] integers = il.getInstructionsAsIntegers();
if (integers != null) {
for (int i : integers) {
System.out.println(i);
}
}
} catch (IOException e) {
// handle
}
}
}
// InstructionList.java
import java.io.*;
public class InstructionList {
private String[] instructions;
public void readFile(String path, int lineLimit) throws IOException {
FileInputStream in = new FileInputStream(path);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
instructions = new String[lineLimit];
for (int i = 0; i < lineLimit; i++) {
instructions[i] = br.readLine();
}
in.close();
}
public String[] getInstructionsAsStrings() {
return instructions; // will return null if uninitialized
}
public int[] getInstructionsAsIntegers() {
if (this.instructions == null) {
return null;
}
int[] instructions = new int[this.instructions.length];
try {
for (int i = 0; i < instructions.length; i++) {
instructions[i] = new Integer(this.instructions[i]);
}
} catch (NumberFormatException e) {
return null; // data integrity fail, return null
}
return instructions;
}
}
check instructionList is null or not. if it is null, call readFile method.
public String[] returnsInstructionList() {
if (instructionList== null){
try { readFile(); } catch(Exception e){}
}
return instructionList;
}
because of readFile can throw exception, it would be good to use one extra variable. like:
private boolean fileReaded = false;
public String[] returnsInstructionList() {
if (!fileReaded){
fileReaded = true;
try { readFile(); } catch(Exception e){}
}
return instructionList;
}
and if readFile can be run concurrently, easiest way to make function synchronized, like
private boolean fileReaded = false;
public synchronized void readFile() throws IOException {
.
.
.
}
public synchronized String[] returnsInstructionList() {
if (!fileReaded){
fileReaded = true;
try { readFile(); } catch(Exception e){}
}
return instructionList;
}
There is no guarantee that readFile is called before returnsInstructionList is invoked. Leaving you returnsInstructionList returning null.
I would :
public String[] getContentsFromFile(String fileName) throws IOException {
FileInputStream in = new FileInputStream(fileName);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
int n = 5;
instructionList = new String[n];
for (int j = 0; j < instructionList.length; j++) {
instructionList[j] = br.readLine();
}
in.close();
return instructionList;
}
Part two to the question you can use generics. To achieve what you want but you have to incorporate a way to say what it is.
Eg
public class Foo {
public ReturnForFoo returnAStringOrIntger(boolean val) {
if(val){
return new ReturnForFoo("String", ValueType.STRING) ;
}
return new ReturnForFoo(10, ValueType.INTEGER); //int
}
}
public class ReturnForFoo {
Object value;
ValueType type;
public ReturnForFoo(Object value, ValueType type) {
this.value=value;
this.type=type
}
// Asume you have getters for both value and value type
public static ENUM ValueType {
STRING,
INTEGER,
UNKNOWN
}
}
This code is in your main.
Foo foo = new Foo();
String value;
int val;
ReturnForFoo returnForFoo = foo.returnAStringOrIntger(true);
// NOTE you can use switch instead of if's and else if's. It will be better
if(returnForFoo.getValueType().equals(ValueType.INTEGER)){
val = (int) returnForFoo.getValue();
} else if(returnForFoo.getValueType().equals(ValueType.STRING)){
value = (String) returnForFoo.getValue();
} else {
// UNKOWN Case
}

Read text line and put in to the JTable

hey
i have text file shown as below.
11/2/2010 cat 6
11/2/2010 cat 3
11/2/2010 dog 4
11/2/2010 cat 11
11/3/2010 cat 1
11/3/2010 dog 3
11/3/2010 cat 8
i have in every month this kind of text file. Above figure shows the part of the text file. so then i want to read this text using java to Jtable.
i Have used StringTokanizer And Arreaylist to ceate this. Unfotunately i couldn't done it. SO PLS HELP ME........
So i want below result to jTable using java program.
date animal total count
11/2/2010 cat 20 3
11/3/2010 cat 9 2
You don't need a StringTokenizer (in fact, it's not recommended). Just get the input line by line using BufferedReader, and do a String split:
List<Array> data = new ArrayList<Array>();
BufferedReader in = new BufferedReader(new FileReader("foo.in"));
String line;
// Read input and put into ArrayList of Arrays
while ((line = in.readLine) != null) {
data.add(line.split("\\s+"));
}
// Now create JTable with Array of Arrays
JTable table = new JTable(data.toArray(), new String[] {
"date", "animal", "total", "count"});
test with : http://crysol.org/es/node/819
or
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;
public class Reader {
public Reader() {
// TODO Auto-generated constructor stub
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
BufferedReader reader;
try {
reader = new BufferedReader(new InputStreamReader(
new FileInputStream("sample.txt")));
Map<String, Object[]> result = new LinkedHashMap<String, Object[]>();
while (reader.ready()) {
String line = reader.readLine();
String[] values = line.split("\\s+");
String key = values[0] + "\t" + values[1];
String label = values[0];
String date = values[1];
Integer sum = 0;
Integer count = 0;
if (result.containsKey(key)) {
sum = (Integer) ((Object[]) result.get(key))[2];
count = (Integer) ((Object[]) result.get(key))[3];
} else {
}
result.put(key, new Object[]{label, date,
sum + Integer.parseInt(values[2]), count + 1});
}
ArrayList arrayList = new ArrayList(result.values());
/* interate and print new output */
/*
* for (String key : result.keySet()) { Integer sum =
* result.get(key); Integer count = result2.get(key);
* System.out.println(key + " " + sum + "\t" + count); }
*/
JTable table = new JTable(new AnimalTableModel(arrayList));
panel.add(new JScrollPane(table));
reader.close();
frame.setContentPane(panel);
frame.setVisible(true);
frame.pack();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new Reader();
}
public class AnimalTableModel implements TableModel {
final Class[] columnClass = new Class[]{String.class, String.class,
Integer.class, Integer.class};
final String[] columnName = new String[]{"Date", "Animal", "Sum",
"Count"};
List values = null;
public AnimalTableModel(List values) {
this.values = values;
// initilize values
}
#Override
public void addTableModelListener(TableModelListener l) {
}
#Override
public Class<?> getColumnClass(int columnIndex) {
return columnClass[columnIndex];
}
#Override
public int getColumnCount() {
return columnClass.length;
}
#Override
public String getColumnName(int columnIndex) {
return columnName[columnIndex];
}
#Override
public int getRowCount() {
return values.size();
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
return ((Object[]) values.get(rowIndex))[columnIndex];
}
#Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
#Override
public void removeTableModelListener(TableModelListener l) {
}
#Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
// TODO FOR EDITABLE DT
}
}
}
You will have to populate the data to a map from the given file.I will give you an example as to how to populate the data.
public class AnimalMapping {
public static void main(String[] args) {
Object[][] data = { { "11/2/2010", "cat", 6 },
{ "11/2/2010", "cat", 3 }, { "11/2/2010", "dog", 4 },
{ "11/2/2010", "cat", 11 }, { "11/3/2010", "cat", 1 },
{ "11/3/2010", "dog", 3 }, { "11/3/2010", "cat", 8 } };
HashMap<String, Map<String, AnimalValCnt>> animalMap = new HashMap<String, Map<String, AnimalValCnt>>();
for (Object[] record : data) {
Map<String, AnimalValCnt> innerMap = null;
if ((innerMap = animalMap.get(record[0])) == null) {
innerMap = new HashMap<String, AnimalValCnt>();
animalMap.put((String) record[0], innerMap);
}
AnimalValCnt obj = null;
if ((obj = innerMap.get(record[1])) == null) {
obj = new AnimalValCnt();
innerMap.put((String) record[1], obj);
}
obj.Sumval += (Integer) record[2];
obj.cnt++;
}
System.out.println(animalMap);
}
}
class AnimalValCnt {
int Sumval;
int cnt;
#Override
public String toString() {
return "(" + Sumval + "," + cnt + ")";
}
}
Once you have got the data in a map then it's easy to populate these data to a table.You can use a tablemodel for this purpose.Have a look at this code to understand how data from a map can be loaded into a table using TableModel.
UPDATE:
public class AnimalMapping {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader in = new BufferedReader(new FileReader("foo.in"));
String line;
String[] record;
HashMap<String, Map<String, AnimalValCnt>> animalMap = new HashMap<String, Map<String, AnimalValCnt>>();
while(((line = in.readLine()) != null)) {
record=line.split("\\s+");
Map<String, AnimalValCnt> innerMap = null;
if ((innerMap = animalMap.get(record[0])) == null) {
innerMap = new HashMap<String, AnimalValCnt>();
animalMap.put(record[0], innerMap);
}
AnimalValCnt obj = null;
if ((obj = innerMap.get(record[1])) == null) {
obj = new AnimalValCnt();
innerMap.put(record[1], obj);
}
obj.Sumval += Integer.valueOf(record[2]);
obj.cnt++;
}
System.out.println(animalMap);
}
}
class AnimalValCnt {
int Sumval;
int cnt;
#Override
public String toString() {
return "(" + Sumval + "," + cnt + ")";
}
}
#Dilantha Chamal: Reading from file was already given by Box9.I just included it in my code.You should be putting some effort here.Maybe you are a beginner that's why I wrote the code.Now try to implement the TableModel by yourself.Just a friendly advice:unless you do it you are never going to learn.
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import com.google.common.base.CharMatcher;
import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Maps;
import com.google.common.io.Files;
import com.google.common.io.LineProcessor;
public class AnimalSummaryBuilder
{
private static final Splitter SPLITTER = Splitter.on(CharMatcher.anyOf(","));
private static final Joiner JOINER = Joiner.on("\t");
#SuppressWarnings("unchecked")
public static void main(final String[] args) throws Exception
{
#SuppressWarnings("rawtypes")
Map<Animal, Summary> result = Files.readLines(new File("c:/1.txt"), Charsets.ISO_8859_1, new LineProcessor() {
private final Map<Animal, Summary> result = Maps.newHashMap();
public Object getResult()
{
return result;
}
public boolean processLine(final String line) throws IOException
{
Iterator<String> columns = SPLITTER.split(line).iterator();
String date = columns.next();
String name = columns.next();
int value = Integer.valueOf(columns.next()).intValue();
Animal currentRow = new Animal(date, name);
if (result.containsKey(currentRow))
{
Summary summary = result.get(currentRow);
summary.increaseCount();
summary.addToTotal(value);
}
else
{
Summary initialSummary = new Summary();
initialSummary.setCount(1);
initialSummary.setTotal(value);
result.put(currentRow, initialSummary);
}
return true;
}
});
for (Map.Entry<Animal, Summary> entry : result.entrySet())
{
Animal animal = entry.getKey();
Summary summary = entry.getValue();
System.out.println(JOINER.join(animal.date, animal.name, summary.total, summary.count));
}
}
final static class Animal
{
String date;
String name;
public Animal(final String date, final String n)
{
this.date = date;
this.name = n;
}
#Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((date == null) ? 0 : date.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
#Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (!(obj instanceof Animal))
{
return false;
}
Animal other = (Animal) obj;
if (date == null)
{
if (other.date != null)
{
return false;
}
}
else if (!date.equals(other.date))
{
return false;
}
if (name == null)
{
if (other.name != null)
{
return false;
}
}
else if (!name.equals(other.name))
{
return false;
}
return true;
}
}
final static class Summary
{
private int total;
private int count;
void setTotal(int value)
{
total = value;
}
void setCount(int i)
{
count = i;
}
void increaseCount()
{
count++;
}
void addToTotal(int valueToAdd)
{
total += valueToAdd;
}
}
}

Categories

Resources