how to fix blank file IO in java [duplicate] - java

This question already has answers here:
Blank file after writing to it?
(3 answers)
Closed 5 years ago.
I am newbie in java programming and learning Io. I am making a simple RPG game but got a problem in my code. it's about the file it's blank whenever i finish running it. somehow whenever I run it I got an empty file. can some one help me :c. (sorry for bad English)
here is my code: FOR RANDOM CLASS
public class Dice {
/** instance variables */
private final Random r;
/**
* Initializes the random number generator r
*/
public Dice() {
r = new Random();
}
/**
* Returns a random integer between 1 and 6 using Random r
* #return
*/
public int roll() {
int dieRoll = r.nextInt(6 - 1);
return dieRoll;
}
}
FOR Character CLASS
public class Character {
static Dice dice = new Dice();
private String name;
private int strength;
private int dexterity;
private int intelligence;
private int maxLife;
private int currentLife;
private int atk;
public Character(){
}
public Character(String n, int s, int d, int i) {
this.name = n;
this.strength = s;
this.dexterity = d;
this.intelligence = i;
this.maxLife = 100 + dice.roll();
this.currentLife = maxLife;
}
/**
* Returns a random die roll using the roll method in the Dice.java,
* *modified by the character's strength
*/
public int attack() {
this.atk = strength * dice.roll() + 24;
return atk;
}
public void wound(int damage) {
if ((currentLife - damage) <= 0) {
this.currentLife = 0;
} else {
this.currentLife = currentLife - damage;
}
}
public void heal(int heal) {
if ((currentLife + heal) < maxLife) {
this.currentLife = currentLife + heal;
} else {
this.currentLife = maxLife;
}
}
public boolean checkDead() {
return currentLife == 0;
}
public String getName() {
return name;
}
public int getStrength() {
return strength;
}
/**
* Returns dexterity
*/
public int getDexterity() {
return dexterity;
}
/**
* * Returns intelligence
*/
public int getIntelligence() {
return intelligence;
}
/**
* Returns currentLife
*/
public int getCurrentLife() {
return currentLife;
}
/**
* Returns maxLife
*/
public int getMaxLife() {
return maxLife;
}
public int getAtk() {
return atk;
}
}
FOR MAIN CLASS(HERE IS WERE THE PROBLEM I DONT KNOW IF I LACK SOMETHING HERE)
public class TestCharacter {
public static void main(String letsPlay[]){
PrintWriter outputStream = null;
try{
outputStream = new PrintWriter(new FileOutputStream("RPGOutput.txt",true));
Scanner s = new Scanner(System.in);
System.out.print("Enter Player 1 Character name:");
Character p1 = new Character(s.next(),s.nextInt(),s.nextInt(),s.nextInt());
System.out.println(p1.getName()+ "\tHAS ENTERED THE BATTLE!");
System.out.println("Enter Player 2 Character name:");
Character p2 = new Character(s.next(),s.nextInt(),s.nextInt(),s.nextInt());
System.out.println(p2.getName()+ "\tHAS ENTERED THE BATTLE!");
int i = 1;
do {
outputStream.println("\nR O U N D " + i + "!");
outputStream.print(p1.getName() + " "+"HP is");
outputStream.println("\t" + p1.getCurrentLife() + "/" + p1.getMaxLife());
outputStream.println("while");
outputStream.print(p2.getName() + " " + " HP is");
outputStream.println("\t" + p2.getCurrentLife() + "/" + p2.getMaxLife());
outputStream.println(" ");
p2.wound(p1.attack());
outputStream.println(p1.getName() + " attacks " + p2.getName() + " for " + p1.getAtk() + " damage!");
if (p2.checkDead() == true) {
outputStream.println(p2.getName() + " lose " + p1.getName() + " has won!");
return;
}
p1.wound(p2.attack());
outputStream.println(p2.getName() + " attacks " + p1.getName() + " for " + p2.getAtk() + " damage!");
if (p1.checkDead() == true) {
outputStream.println(p1.getName() + " lose " + p2.getName() + " has won!");
return;
}
i++;
} while (p1.checkDead() == false || p2.checkDead() == false);
}catch(FileNotFoundException e){
System.out.println("Error no file" + e);
System.exit(0);
}
}
}

When you open a stream you should always finally close it.
In java 1.7 and above you just try( ... open the stream here ){ ... useit ...}, the compilers adds the finally close implicitly .
You need to finally close to be sure you don't leave open resources allocated.
It could be wise to set the PrintWriter to autoflush or make sure you flush before closing the stream, if not so maybe the PrintWriter does not write to the output stream until is buffer is full.
Java 1.6 and below
OutputStream fos = null;
try{
fos = new FileOutputStream("RPGOutput.txt",true);
PrintWriter out = new PrintWriter(fos, true);
out.println("Someting");
out.println("...");
//
out.flush();
}catch(IOException e){
// Manage exception
} finally {
try{
if(fos!=null){
fos.close();
}
}catch(IOException e){
// Swallow exception
}
}
Java 1.7 and above
try(OutputStream fos = new FileOutputStream("RPGOutput2.txt",true);
PrintWriter out = new PrintWriter(fos,true);) {
out.println("Hello");
out.print("Hello 2");
} catch (IOException e) {
// Manage exception
}

Related

Removing statics from project

Is their an easy way to pass the variables and arrays between these methods without having a super long method signature? Currently I am using these statics but I know that's not the "correct" way of doing it but if I pass them in the signature it starts to make everything look ugly. So what would be the "correct" way to pass the variables like lastName, firstName, and role?
// Program wide variables
//static String firstName; // First name from the file
static String lastName; // Last name from the file
static String username; // Username
static String password;
static String role;
static String email;
static String answersFile; // Answers file in use with path and ext
static String[] answeredQ = new String[questAsks]; // Recording the question asked
static Boolean[] answeredA = new Boolean[questAsks]; //Recording users answer
static Boolean[] answeredC = new Boolean[questAsks]; //Recording the correct answer
public static void main(String Args[]) throws FileNotFoundException, IOException {
// Main method that contains major control functions; a quick summary of the program; magic
}
public static void quiz(String testType) throws HeadlessException, IOException {
String testBankFile = path + testType + ".txt";
Random rand = new Random();
int questionCount = 0, right = 0, wrong = 0;
long startTime = System.currentTimeMillis(); // Setting the start time in milliseconds
while (questionCount < questAsks) { // Loop that will ask all the questions
int r = rand.nextInt(getLines(testBankFile));
boolean ans = promptQuestion(read(r, testBankFile), questionCount + 1); // For some reason this makes it work
answeredQ[questionCount] = read(r, testBankFile);
answeredA[questionCount] = ans;
answeredC[questionCount] = parseA(read(r, answersFile));
if (ans != parseA(read(r, answersFile))) {
wrong++;
} else if (ans == parseA(read(r, answersFile))) {
right++;
}
questionCount++;
}
JOptionPane.showMessageDialog(null, "You got " + wrong + " wrong and " + right + " correct.");
long endDiff = (System.currentTimeMillis() - startTime);
makeReport(firstName, lastName, username, printTime(endDiff), testType, right);
}
// Generates a report report(first, last, score, time, array of answers)
public static void makeReport(String first, String last, String user, String time, String testType, int score) throws IOException {
DateFormat dateF = new SimpleDateFormat(dateFormat);
Date date = new Date();
String fileName = user + "_COSC236_Quiz_" + dateF.format(date) + ".txt";
File file = new File(fileName);
file.createNewFile();
FileWriter out = new FileWriter(fileName);
double percent = (((double) score) / ((double) questAsks) * 100);
out.write("Name: " + first + " " + last + "\n");
out.write("Score: " + percent + "%\n");
out.write("Elapsed time: " + time + "\n");
out.write("Test type: " + testType + "\n");
out.write("---------------------------------------------------------------------\n");
out.write(" Users\tCorrect\tQuestion\n");
for (int i = 0; i < answeredQ.length; i++) {
out.write(i + 1 + ".) ");
out.write(answeredA[i].toString() + "\t");
out.write(answeredC[i].toString() + "\t");
out.write(answeredQ[i] + "\n");
}
out.close();
}
// Boolean login method | login(tries allowed, source file)
public static void login(int tries, String source) throws FileNotFoundException, IOException {
String[] loginInfo;
boolean invalid = false;
for (int x = 0; x < tries; x++) {
invalid = false;
loginInfo = promptLogin();
if (loginInfo[0].toLowerCase().equals("done")) {
System.exit(0);
}
for (int i = 0; i < getLines(source); i++) {
StringTokenizer st = null;
st = new StringTokenizer(read(i, source));
String user = st.nextToken();
String pass = st.nextToken();
if (user.equals(loginInfo[0])) {
if (pass.equals(loginInfo[1])) {
username = loginInfo[0];
password = loginInfo[1];
firstName = st.nextToken();
lastName = st.nextToken();
email = st.nextToken();
role = st.nextToken();
if (role.toLowerCase().equals("instructor")) {
promptInstructor();
JOptionPane.showMessageDialog(null, exitedInstructorMode);
break;
} else {
run();
}
} else {
invalid = true;
}
} else {
invalid = true;
}
}
if(invalid) {
JOptionPane.showMessageDialog(null, invalidLogin);
}
}
JOptionPane.showMessageDialog(null, tooManyAttempts);
}
}
Why not just make a class that holds the values that you need to pass around
Use OOP. Create clss to you object
example:
class User{
String lastName;
String username;
String password;
String role;
String email;
...
public static User login(int tries, String source) throws FileNotFoundException, IOException {
//this you read User param and add new User
return user;
}
}
And now, where you need lastName, username, password, role or email, you can
pass User instance

Exception in thread "main" java.lang.IllegalArgumentException: bound must be positive

import java.util.Random;
import java.util.StringTokenizer;
public class FortuneCookie {
private String subjList;
private String objList;
private String verbList;
private int sWords = 0;
private int oWords = 0;
private int vWords = 0;
private Random random = new Random();
public FortuneCookie() {
subjList = "i#You#He#She#It#They";
objList = "me#you#him#her#it#them";
verbList = "hate#love#deny#find#hear#forgive#hurt#win#teach";
}
public void setSubject(String subj) {
subjList = subj;
}
public void setObjectList(String obj) {
objList = obj;
}
public void setVerbList(String verb) {
verbList = verb;
}
public String genFortuneMsg() {
String v = " ";
String o = " ";
String s = " ";
StringTokenizer st1 = new StringTokenizer(subjList, "#");
StringTokenizer st2 = new StringTokenizer(objList, "#");
StringTokenizer st3 = new StringTokenizer(verbList, "#");
while (st1.hasMoreTokens()) {
s = st1.nextToken();
sWords = st1.countTokens();
int no = random.nextInt(sWords);
if (no == sWords) {
break;
}
}
while (st2.hasMoreTokens()) {
o = st2.nextToken();
oWords = st2.countTokens();
int no2 = random.nextInt(oWords);
if (no2 == oWords) {
break;
}
}
while (st3.hasMoreTokens()) {
v = st3.nextToken();
vWords = st3.countTokens();
int no3 = random.nextInt(vWords);
if (no3 == vWords) {
break;
}
}
String gen = s + " " + v + " " + o;
return gen;
}
public void print() {
System.out.println("Tokens");
System.out.println("Subject List:" + subjList + " count = " + sWords);
System.out.println("verb List:" + verbList + " count = " + vWords);
System.out.println("object List:" + objList + " count = " + oWords);
}
}
Exception in thread "main" java.lang.IllegalArgumentException: bound
must be positive at java.util.Random.nextInt(Random.java:388) at
FortuneCookie.genFortuneMsg(FortuneCookie.java:42) at
FortuneCookieTest.main(FortuneCookieTest.java:6)
Your case is not negative it is zero.
From the docs of countToken method
/**
* Calculates the number of times that this tokenizer's
* <code>nextToken</code> method can be called before it generates an
* exception. The current position is not advanced.
*
In a while loop when your count token return zero, you run into an exception. Well that error message should be reformatted to negative or zero.
Add 1 to your result or check for zero. Should work.

Tiny GP output in text file

I've recently stumbled upon Tiny GP (A Genetic Programming program), and I found it pretty useful, so I decided to change all System.out.println() in the program to a write to text file method.
Problem: In the text file, for some reason, only says "PROBLEM SOLVED", instead of printing out generations and other things that it is supposed to (see code).
Tiny GP modified class file:
package main;
/*
* Program: tiny_gp.java
*
* Author: Riccardo Poli (email: rpoli#essex.ac.uk)
*
* Modified by Preston Tang
*/
import java.util.*;
import java.io.*;
import java.text.DecimalFormat;
public class tiny_gp {
String Name;
double[] fitness;
char[][] pop;
static Random rd = new Random();
static final int ADD = 110,
SUB = 111,
MUL = 112,
DIV = 113,
FSET_START = ADD,
FSET_END = DIV;
static double[] x = new double[FSET_START];
static double minrandom, maxrandom;
static char[] program;
static int PC;
static int varnumber, fitnesscases, randomnumber;
static double fbestpop = 0.0, favgpop = 0.0;
static long seed;
static double avg_len;
static final int MAX_LEN = 10000,
POPSIZE = 100000,
DEPTH = 5,
GENERATIONS = 100,
TSIZE = 2;
public static final double PMUT_PER_NODE = 0.05,
CROSSOVER_PROB = 0.9;
public static double[][] targets;
public double run() {
/* Interpreter */
char primitive = program[PC++];
if (primitive < FSET_START) {
return (x[primitive]);
}
switch (primitive) {
case ADD:
return (run() + run());
case SUB:
return (run() - run());
case MUL:
return (run() * run());
case DIV: {
double num = run(), den = run();
if (Math.abs(den) <= 0.001) {
return (num);
} else {
return (num / den);
}
}
}
return (0.0); // should never get here
}
public int traverse(char[] buffer, int buffercount) {
if (buffer[buffercount] < FSET_START) {
return (++buffercount);
}
switch (buffer[buffercount]) {
case ADD:
case SUB:
case MUL:
case DIV:
return (traverse(buffer, traverse(buffer, ++buffercount)));
}
return (0); // should never get here
}
public void setup_fitness(String fname) {
try {
int i, j;
String line;
BufferedReader in
= new BufferedReader(
new FileReader(fname));
line = in.readLine();
StringTokenizer tokens = new StringTokenizer(line);
varnumber = Integer.parseInt(tokens.nextToken().trim());
randomnumber = Integer.parseInt(tokens.nextToken().trim());
minrandom = Double.parseDouble(tokens.nextToken().trim());
maxrandom = Double.parseDouble(tokens.nextToken().trim());
fitnesscases = Integer.parseInt(tokens.nextToken().trim());
targets = new double[fitnesscases][varnumber + 1];
if (varnumber + randomnumber >= FSET_START) {
Write("too many variables and constants");
//System.out.println("too many variables and constants");
}
for (i = 0; i < fitnesscases; i++) {
line = in.readLine();
tokens = new StringTokenizer(line);
for (j = 0; j <= varnumber; j++) {
targets[i][j] = Double.parseDouble(tokens.nextToken().trim());
}
}
in.close();
} catch (FileNotFoundException e) {
Write("ERROR: Please provide a data file");
//System.out.println("ERROR: Please provide a data file");
System.exit(0);
} catch (Exception e) {
Write("ERROR: Incorrect data format");
//System.out.println("ERROR: Incorrect data format");
System.exit(0);
}
}
public double fitness_function(char[] Prog) {
int i = 0, len;
double result, fit = 0.0;
len = traverse(Prog, 0);
for (i = 0; i < fitnesscases; i++) {
for (int j = 0; j < varnumber; j++) {
x[j] = targets[i][j];
}
program = Prog;
PC = 0;
result = run();
fit += Math.abs(result - targets[i][varnumber]);
}
return (-fit);
}
public int grow(char[] buffer, int pos, int max, int depth) {
char prim = (char) rd.nextInt(2);
int one_child;
if (pos >= max) {
return (-1);
}
if (pos == 0) {
prim = 1;
}
if (prim == 0 || depth == 0) {
prim = (char) rd.nextInt(varnumber + randomnumber);
buffer[pos] = prim;
return (pos + 1);
} else {
prim = (char) (rd.nextInt(FSET_END - FSET_START + 1) + FSET_START);
switch (prim) {
case ADD:
case SUB:
case MUL:
case DIV:
buffer[pos] = prim;
one_child = grow(buffer, pos + 1, max, depth - 1);
if (one_child < 0) {
return (-1);
}
return (grow(buffer, one_child, max, depth - 1));
}
}
return (0); // should never get here
}
public int print_indiv(char[] buffer, int buffercounter) {
int a1 = 0, a2;
if (buffer[buffercounter] < FSET_START) {
if (buffer[buffercounter] < varnumber) {
Write("X" + (buffer[buffercounter] + 1) + " ");
//System.out.print("X" + (buffer[buffercounter] + 1) + " ");
} else {
WriteDouble(x[buffer[buffercounter]]);
//System.out.print(x[buffer[buffercounter]]);
}
return (++buffercounter);
}
switch (buffer[buffercounter]) {
case ADD:
Write("(");
//System.out.print("(");
a1 = print_indiv(buffer, ++buffercounter);
Write(" + ");
//System.out.print(" + ");
break;
case SUB:
Write("(");
//System.out.print("(");
a1 = print_indiv(buffer, ++buffercounter);
Write(" - ");
//System.out.print(" - ");
break;
case MUL:
Write("(");
//System.out.print("(");
a1 = print_indiv(buffer, ++buffercounter);
Write(" * ");
//System.out.print(" * ");
break;
case DIV:
Write("(");
//System.out.print("(");
a1 = print_indiv(buffer, ++buffercounter);
Write(" / ");
//System.out.print(" / ");
break;
}
a2 = print_indiv(buffer, a1);
Write(")");
//System.out.print(")");
return (a2);
}
public static char[] buffer = new char[MAX_LEN];
public char[] create_random_indiv(int depth) {
char[] ind;
int len;
len = grow(buffer, 0, MAX_LEN, depth);
while (len < 0) {
len = grow(buffer, 0, MAX_LEN, depth);
}
ind = new char[len];
System.arraycopy(buffer, 0, ind, 0, len);
return (ind);
}
public char[][] create_random_pop(int n, int depth, double[] fitness) {
char[][] pop = new char[n][];
int i;
for (i = 0; i < n; i++) {
pop[i] = create_random_indiv(depth);
fitness[i] = fitness_function(pop[i]);
}
return (pop);
}
public void stats(double[] fitness, char[][] pop, int gen) {
int i, best = rd.nextInt(POPSIZE);
int node_count = 0;
fbestpop = fitness[best];
favgpop = 0.0;
for (i = 0; i < POPSIZE; i++) {
node_count += traverse(pop[i], 0);
favgpop += fitness[i];
if (fitness[i] > fbestpop) {
best = i;
fbestpop = fitness[i];
}
}
avg_len = (double) node_count / POPSIZE;
favgpop /= POPSIZE;
Write("Generation=" + gen + " Avg Fitness=" + (-favgpop)
+ " Best Fitness=" + (-fbestpop) + " Avg Size=" + avg_len
+ "\nBest Individual: ");
//System.out.print("Generation=" + gen + " Avg Fitness=" + (-favgpop)
// + " Best Fitness=" + (-fbestpop) + " Avg Size=" + avg_len
// + "\nBest Individual: ");
print_indiv(pop[best], 0);
Write("\n");
//System.out.print("\n");
//System.out.flush();
}
public int tournament(double[] fitness, int tsize) {
int best = rd.nextInt(POPSIZE), i, competitor;
double fbest = -1.0e34;
for (i = 0; i < tsize; i++) {
competitor = rd.nextInt(POPSIZE);
if (fitness[competitor] > fbest) {
fbest = fitness[competitor];
best = competitor;
}
}
return (best);
}
public int negative_tournament(double[] fitness, int tsize) {
int worst = rd.nextInt(POPSIZE), i, competitor;
double fworst = 1e34;
for (i = 0; i < tsize; i++) {
competitor = rd.nextInt(POPSIZE);
if (fitness[competitor] < fworst) {
fworst = fitness[competitor];
worst = competitor;
}
}
return (worst);
}
public char[] crossover(char[] parent1, char[] parent2) {
int xo1start, xo1end, xo2start, xo2end;
char[] offspring;
int len1 = traverse(parent1, 0);
int len2 = traverse(parent2, 0);
int lenoff;
xo1start = rd.nextInt(len1);
xo1end = traverse(parent1, xo1start);
xo2start = rd.nextInt(len2);
xo2end = traverse(parent2, xo2start);
lenoff = xo1start + (xo2end - xo2start) + (len1 - xo1end);
offspring = new char[lenoff];
System.arraycopy(parent1, 0, offspring, 0, xo1start);
System.arraycopy(parent2, xo2start, offspring, xo1start,
(xo2end - xo2start));
System.arraycopy(parent1, xo1end, offspring,
xo1start + (xo2end - xo2start),
(len1 - xo1end));
return (offspring);
}
public char[] mutation(char[] parent, double pmut) {
int len = traverse(parent, 0), i;
int mutsite;
char[] parentcopy = new char[len];
System.arraycopy(parent, 0, parentcopy, 0, len);
for (i = 0; i < len; i++) {
if (rd.nextDouble() < pmut) {
mutsite = i;
if (parentcopy[mutsite] < FSET_START) {
parentcopy[mutsite] = (char) rd.nextInt(varnumber + randomnumber);
} else {
switch (parentcopy[mutsite]) {
case ADD:
case SUB:
case MUL:
case DIV:
parentcopy[mutsite]
= (char) (rd.nextInt(FSET_END - FSET_START + 1)
+ FSET_START);
}
}
}
}
return (parentcopy);
}
public void print_parms() {
Write("-- TINY GP (Java version) --\n");
//System.out.print("-- TINY GP (Java version) --\n");
Write("SEED=" + seed + "\nMAX_LEN=" + MAX_LEN
+ "\nPOPSIZE=" + POPSIZE + "\nDEPTH=" + DEPTH
+ "\nCROSSOVER_PROB=" + CROSSOVER_PROB
+ "\nPMUT_PER_NODE=" + PMUT_PER_NODE
+ "\nMIN_RANDOM=" + minrandom
+ "\nMAX_RANDOM=" + maxrandom
+ "\nGENERATIONS=" + GENERATIONS
+ "\nTSIZE=" + TSIZE
+ "\n----------------------------------\n");
// System.out.print("SEED=" + seed + "\nMAX_LEN=" + MAX_LEN
// + "\nPOPSIZE=" + POPSIZE + "\nDEPTH=" + DEPTH
// + "\nCROSSOVER_PROB=" + CROSSOVER_PROB
// + "\nPMUT_PER_NODE=" + PMUT_PER_NODE
// + "\nMIN_RANDOM=" + minrandom
// + "\nMAX_RANDOM=" + maxrandom
// + "\nGENERATIONS=" + GENERATIONS
// + "\nTSIZE=" + TSIZE
// + "\n----------------------------------\n");
}
public tiny_gp(String fname, long s) {
fitness = new double[POPSIZE];
seed = s;
if (seed >= 0) {
rd.setSeed(seed);
}
setup_fitness(fname);
for (int i = 0; i < FSET_START; i++) {
x[i] = (maxrandom - minrandom) * rd.nextDouble() + minrandom;
}
pop = create_random_pop(POPSIZE, DEPTH, fitness);
}
public void evolve() {
int gen = 0, indivs, offspring, parent1, parent2, parent;
double newfit;
char[] newind;
print_parms();
stats(fitness, pop, 0);
for (gen = 1; gen < GENERATIONS; gen++) {
if (fbestpop > -1e-5) {
Write("PROBLEM SOLVED\n");
//System.out.print("PROBLEM SOLVED\n");
System.exit(0);
}
for (indivs = 0; indivs < POPSIZE; indivs++) {
if (rd.nextDouble() < CROSSOVER_PROB) {
parent1 = tournament(fitness, TSIZE);
parent2 = tournament(fitness, TSIZE);
newind = crossover(pop[parent1], pop[parent2]);
} else {
parent = tournament(fitness, TSIZE);
newind = mutation(pop[parent], PMUT_PER_NODE);
}
newfit = fitness_function(newind);
offspring = negative_tournament(fitness, TSIZE);
pop[offspring] = newind;
fitness[offspring] = newfit;
}
stats(fitness, pop, gen);
}
Write("PROBLEM *NOT* SOLVED\n");
//System.out.print("PROBLEM *NOT* SOLVED\n");
System.exit(1);
}
public void Write(String context) {
FileWriter fileWriter;
try {
fileWriter = new FileWriter("GP.txt");
try (BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)) {
bufferedWriter.write(context);
}
} catch (IOException ex) {
}
}
public void WriteDouble(double context) {
FileWriter fileWriter;
try {
fileWriter = new FileWriter("GP.txt");
try (BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)) {
String ncontext = Double.toString(context);
bufferedWriter.write(ncontext);
}
} catch (IOException ex) {
}
}
};
The Functions Mapper file that uses the Tiny GP class file:
package function_mapper;
import javax.swing.JOptionPane;
import main.*;
public class Function_Mapper {
public static void main(String[] args) {
String fname = JOptionPane.showInputDialog(null, "File Name", "Input Dialog", JOptionPane.INFORMATION_MESSAGE);
long s = -1;
if (args.length == 2) {
s = Integer.valueOf(args[0]).intValue();
fname = args[1];
}
if (args.length == 1) {
fname = args[0];
}
tiny_gp gp = new tiny_gp(fname, s);
gp.evolve();
}
}
Much help appreciated, thanks!
The Write method overwrites the contents of the file on each invocation. There are two ways to fix this.
An easier one, is to append file, instead of overwriting it. It could be achieved by passing append argument to the FileWriter (I simplified code a little bit along the way).
// true on the next line means "append"
try (Writer writer = new FileWriter("GP.txt", true)) {
writer.write(Double.toString(context));
} catch (IOException ex) {
}
A harder, but much fore efficient one is to openwriter in the constructor, use it in Write method, and close in the specially introduced close method of the tiny_gp.

Not reading a file?

So I want to read a text file but for some strange reason it can't find the file. I have used these methods before, and I therefore have no idea why this isn't working can someone please help me out?
EDIT:
sorry guys I left out a big piece of info which is that it can find the file when it is writing to it but not when it is reading from it. Thanks for all your guys' help and sorry for wasting your time asking a question I didn't need the answer to... Again sorry.
Some more info:
"Assets.txt" is in both the project's root folder as well as in the src/assetregistry
"Assets.txt" will be there when the program is run
All I get is the JOption messege from the catch exception in the readFromFile() method
According to the properties of assetRegistry the working directory is
"C:\Users\Justin\Documents\NetBeansProjects\assetregistry\src\assetregistry"
Thank you to everyone who helped, especially Chris and Andrew Thompson. The program now work and the following is the updated version. Feel free to copy it if you want. It's really a simple program.
Main class:
package assetregistry;
import java.io.IOException;
import javax.swing.JOptionPane;
public class Assetregistry {
public static void main(String[] args) throws IOException {
new Assetregistry();
}
assetArray aa = new assetArray();
public Assetregistry() throws IOException {
aa.readFromFile ();
char choice = 'Z';
while (choice != 'X') {
choice = menu();
options(choice);
}
}
public char menu() {
char ch = JOptionPane.showInputDialog("\t" + "Welcome to asset registry. Please input your choice" + "\n" + "A: Enter new asset" + "\n" + "B: Calculate depreciation and display" + "\n" + "X: Exit").toUpperCase().charAt(0);
return ch;
}
private void options(char c) throws IOException {
switch (c) {
case 'A':
aa.enterAsset();
break;
case 'B':
aa.calculate();
break;
case 'X':
System.exit(0);
break;
}
}
}
Array/method class
package assetregistry;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import javax.swing.JOptionPane;
public class assetArray {
asset[] aArr = new asset[100];
private double year;
private double month;
private int count = 0;
Assetregistry AR;
String home = System.getProperty("user.home");
File userHome = new File(home);
File file = new File(userHome,"Assets.txt");
public assetArray() throws IOException {
}
public void enterAsset() throws IOException {
int choice = JOptionPane.YES_OPTION;
while (choice == JOptionPane.YES_OPTION) {
String name = JOptionPane.showInputDialog("Enter asset name");
double costP = Double.parseDouble(JOptionPane.showInputDialog("Enter the cost price of the asset"));
int lSpan = Integer.parseInt(JOptionPane.showInputDialog("Enter the amount of years you wish to keep the asset"));
double mBought = Double.parseDouble(JOptionPane.showInputDialog("Enter the month the asset was bought (As a number)"));
double yBought = Double.parseDouble(JOptionPane.showInputDialog("Enter the year the asset was bought"));
double depr = (1.00 / lSpan * 100.00);
aArr[count] = new asset(name, costP, lSpan, yBought, mBought, depr);
PrintWriter pw = new PrintWriter(new FileWriter(file, true));
pw.println(aArr[count].toString());
pw.close();
count++;
choice = JOptionPane.showConfirmDialog(null, " Do you want to enter another asset?", " Enter another asset?", JOptionPane.YES_NO_OPTION);
}
}
public void calculate() {
String name;
int lSpan;
double ybought;
double mbought;
double pValue;
double Rate;
double deprExp;
double numYears;
double fValue;
double accDepr;
String[] mnth = new String[12];
mnth[0] = "January";
mnth[1] = "February";
mnth[2] = "March";
mnth[3] = "April";
mnth[4] = "May";
mnth[5] = "June";
mnth[6] = "July";
mnth[7] = "August";
mnth[8] = "September";
mnth[9] = "October";
mnth[10] = "November";
mnth[11] = "December";
if (count > 0) {
year = Integer.parseInt(JOptionPane.showInputDialog("Enter the year you wish to calculate depreciation for"));
month = Integer.parseInt(JOptionPane.showInputDialog("Enter the month you wish to calculate depreciation for"));
int m = (int) month;
int y = (int) year;
System.out.println("Asset regestry" + "\t" + mnth[m-1] + " " + y);
for (int i = 0; i < count; i++) {
name = aArr[i].getName();
lSpan = aArr[i].getLifeSpan();
ybought = aArr[i].getyBought();
mbought = aArr[i].getmBought();
pValue = aArr[i].getCostP();
Rate = aArr[i].getDeprR();
int m2 = (int) mbought;
int y2 = (int) ybought;
deprExp = pValue - (pValue * ((1.00 - ((Rate))) * 1.00 / 100.00));
numYears = (year + (month / 12.00)) - (ybought + mbought / 12.00);
fValue = pValue * (1.00 - (((Rate) * (numYears)) / 100.00));
if (fValue <= 0.00) {
fValue = (int) 1;
}
accDepr = pValue - fValue;
System.out.println("\n" + "Asset: " + name);
System.out.println("Life span: " + lSpan + "yrs");
System.out.println("Cost price: " + "R" + pValue);
System.out.println("Date acquired: " + mnth[m2-1] + " " + y2);
System.out.println("Depreciatin rate (p.a.): " + Rate + "%");
System.out.println("Depreciation(p.a.): R" + deprExp);
System.out.println("Accumulated depreciation: R" + accDepr);
System.out.println("Current book value: R" + fValue);
System.out.println("_________________________________________");
}
} else {
JOptionPane.showMessageDialog(null, "There are no assets in memory", "NO ASSETS!", JOptionPane.ERROR_MESSAGE);
}
}
/**
*
*/
public void readFromFile() {
String line = "";
try {
BufferedReader fr = new BufferedReader(new FileReader(file));
line = fr.readLine();
while (line != null) {
StringTokenizer stk = new StringTokenizer(line, "#");
String name = stk.nextToken();
double costP = Double.parseDouble(stk.nextToken());
int lSpan = Integer.parseInt(stk.nextToken());
double yBought = Double.parseDouble(stk.nextToken());
double mBought = Double.parseDouble(stk.nextToken());
double deprR = Double.parseDouble(stk.nextToken());
aArr[count] = new asset(name, costP, lSpan, yBought, mBought, deprR);
count++;
line = fr.readLine();
}
fr.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "There is a file missing.", "FILE MISSING!", JOptionPane.ERROR_MESSAGE);
}
}
}
Assets class
package assetregistry;
/**
*
* #author Justin
*/
public class asset {
private String name;
private double costP;
private int lifeSpan;
private double yBought;
private double mBought;
private double deprR;
public asset(){
}
public asset(String name, double costP, int lifeSpan, double yBought, double mBought, double deprR) {
this.name = name;
this.costP = costP;
this.lifeSpan = lifeSpan;
this.yBought = yBought;
this.mBought = mBought;
this.deprR = deprR;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getCostP() {
return costP;
}
public void setCostP(double costP) {
this.costP = costP;
}
public int getLifeSpan() {
return lifeSpan;
}
public void setLifeSpan(int lifeSpan) {
this.lifeSpan = lifeSpan;
}
public double getyBought() {
return yBought;
}
public void setyBought(double yBought) {
this.yBought = yBought;
}
public double getmBought() {
return mBought;
}
public void setmBought(double mBought) {
this.mBought = mBought;
}
public double getDeprR() {
return deprR;
}
public void setDeprR(double deprR) {
this.deprR = deprR;
}
#Override
public String toString ()
{
String stg = "";
stg += name + "#" + costP + "#" + lifeSpan + "#" + yBought + "#" + mBought + "#" + deprR + "#";
return stg;
}
}
String home = System.getProperty("user.home");
System.out.println("User home directory is: " + home);
File userHome = new File(home);
// Put files in a known and reproducible path!
File file = new File(userHome, "Assets.txt");
It depends where you have put "Assets.txt" in your file system. If you are running the code from inside netbeans, then the line:
File file = new File("Assets.txt");
will be looking for the file in the root folder of your project e.g. */NetBeansProjects/INSERT_PROJECT_NAME/ (if you're not then it will be looking for the file in the same directory the application is running in).I noticed you have the line:
URL url = AR.getClass().getResource("/Assets.txt");
but you never use url in your code. Are you trying to look for the file in the same directory as your "Assetregistry" class and forgot to use url to specify the location? If this is the case then remove the "/" from the beginning of the name and construct the file like this:
URL url = Assetregistry.class.getResource("Assets.txt");
File file = new File(url.toURI());
Hope this helps :)

How to parse a String into multiple arrays

Good day!
I am making a mini bookstore program and we are required to read a file based from what the customer buys on the specified counter as follows:
counter 4,book1 2,book2 2,book3 2,tender 100.00
counter 1,book1 2,book2 1,book3 3, book4 5,tender 200.00
counter 1,book3 1,tender 50.00
In short the format is:
COUNTER -> ITEMS BOUGHT -> TENDER
I tried doing this but it is not that efficient:
public List<String> getOrder(int i) {
List <String> tempQty = new ArrayList<String>();
String[] orders = orderList.get(0).split(",");
for (String order : orders) {
String[] fields = order.split(" ");
tempQty.add(fields[i]);
}
return tempQty;
}
How can i read the file and at the same time, ensures that I will put it on the correct array? Besides the counter and the tender, I need to know the name of the book and the qty so I could get its price and computer for the total price. Do I need to do multiple arrays to store each values? Any suggestions/ codes will be
highly appreciated.
Thank you.
Map<String, Integer> itemsBought = new HashMap<String, Integer>();
final String COUNTER = "counter";
final String TENDER = "tender";
String[] splitted = s.split(",");
for (String str : splitted) {
str = str.trim();
if (str.startsWith(COUNTER)) {
//do what you want with counter
} else if (str.startsWith(TENDER)) {
//do what you want with tender
} else {
//process items, e.g:
String[] itemInfo = str.split(" ");
itemsBought.put(itemInfo[0], Integer.valueOf(itemInfo[1]));
}
}
How about this? Here we have a class that is modeling a purchase, containing counter, tender and a list of the bought items. The bought item consists of an id (e.g. book1) and a quantity. Use the method readPurchases() to read the contents of a file and get a list of purchases.
Does this solve your problem?
public class Purchase {
private final int counter;
private final List<BoughtItem> boughtItems;
private final double tender;
public Purchase(int counter, List<BoughtItem> boughtItems, double tender) {
this.counter = counter;
this.boughtItems = new ArrayList<BoughtItem>(boughtItems);
this.tender = tender;
}
public int getCounter() {
return counter;
}
public List<BoughtItem> getBoughtItems() {
return boughtItems;
}
public double getTender() {
return tender;
}
}
public class BoughtItem {
private final String id;
private final int quantity;
public BoughtItem(String id, int quantity) {
this.id = id;
this.quantity = quantity;
}
public String getId() {
return id;
}
public int getQuantity() {
return quantity;
}
}
public class Bookstore {
/**
* Reads purchases from the given file.
*
* #param file The file to read from, never <code>null</code>.
* #return A list of all purchases in the file. If there are no
* purchases in the file, i.e. the file is empty, an empty list
* is returned
* #throws IOException If the file cannot be read or does not contain
* correct data.
*/
public List<Purchase> readPurchases(File file) throws IOException {
List<Purchase> purchases = new ArrayList<Purchase>();
BufferedReader lines = new BufferedReader(new FileReader(file));
String line;
for (int lineNum = 0; (line = lines.readLine()) != null; lineNum++) {
String[] fields = line.split(",");
if (fields.length < 2) {
throw new IOException("Line " + lineNum + " of file " + file + " has wrong number of fields");
}
// Read counter field
int counter;
try {
String counterField = fields[0];
counter = Integer.parseInt(counterField.substring(counterField.indexOf(' ') + 1));
} catch (Exception ex) {
throw new IOException("Counter field on line " + lineNum + " of file " + file + " corrupt");
}
// Read tender field
double tender;
try {
String tenderField = fields[fields.length - 1];
tender = Double.parseDouble(tenderField.substring(tenderField.indexOf(' ') + 1));
} catch (Exception ex) {
throw new IOException("Tender field on line " + lineNum + " of file " + file + " corrupt");
}
// Read bought items
List<BoughtItem> boughtItems = new ArrayList<BoughtItem>();
for (int i = 1; i < fields.length - 1; i++) {
String id;
int quantity;
try {
String bookField = fields[i];
id = bookField.substring(0, bookField.indexOf(' '));
quantity = Integer.parseInt(bookField.substring(bookField.indexOf(' ') + 1));
BoughtItem boughtItem = new BoughtItem(id, quantity);
boughtItems.add(boughtItem);
} catch (Exception ex) {
throw new IOException("Cannot read items from line " + lineNum + " of file " + file);
}
}
// We're done with this line!
Purchase purchase = new Purchase(counter, boughtItems, tender);
purchases.add(purchase);
}
return purchases;
}
}

Categories

Resources