How to update numbers of an existing text file? - java

Here is my code: https://pastebin.com/1Cmg5Rt8
The program asks the user for their name.
It then generates random math problems, and counts correct answers and incorrect answers.
The user is rewarded $0.05 for correct answers and penalized $0.03 for incorrect answers.
All of the above has been done.
I am stuck starting from here:
A file is created using their name.
The amount of answers they got correct/incorrect are recorded to a text file.
If a file under their name already exists, I must combine their results with the results of the ones on the file.
Example of existing text file:
Correct answers: 1
Incorrect answers: 0
Earnings: $0.05
If the user runs the program again and gets 1 correct answer, it must be updated like this:
Correct answers: 2
Incorrect answers: 0
Earnings: $0.10
Currently, instead of updating, it is being overwritten.
If I choose show stats at the beginning, this is the result (it uses the initialized values):
Correct answers:0
Incorrect answers: 0
Earnings: $0.00
I have spent hours trying to figure this out. I refuse to sleep until I solve this. Someone please help me. I will greatly appreciate it.

You need to read the name in /before/ you retrieve the stats, i.e. your main method should look like this:
public static void main(String[] args) {
validateCreditsResponse();
name();
retrieveStats();
menu();
saveStats();
}
Also, in this method, you need to also output a println like you do in the 'else' branch:
if (money > 0) {
outputfile.printf("Earnings: $%.2f", money);
// Add outputfile.println();
}
Finally, in this method you need to read in the data:
//Creates new text file for the user unless one already exists.
public static void retrieveStats() {
try {
writer = new FileWriter(userName + "Stats.txt", true);
outputfile = new PrintWriter (writer);
} catch (IOException e) {
}
}
You would start doing this with a FileReader, rather than a FileWriter.
For example in Java 8, like this:
//Reads existing text file for the user.
public static void retrieveStats() {
try (BufferedReader br = new BufferedReader(new FileReader(userName + "Stats.txt"))) {
String line;
while ((line = br.readLine()) != null) {
Matcher correctMatcher = Pattern.compile("Correct Answers:(.*)").matcher(line);
if (correctMatcher.matches()) {
correct = Integer.valueOf(correctMatcher.group(1));
}
// TODO complete other matchers
}
} catch (IOException e) {
}
}

Related

Why does BufferedWriter refuse to write a file?

I am making a snake game for my class project in school. Everything was fine until I looked at my code. It produced no errors when I "build" it but returns NumberFormatException.
P.S I am only a 1st year college student. Please be gentle
private void checkScore() throws IOException{
try{
bw = new BufferedWriter(new FileWriter("scores.txt"));
if(score > Integer.parseInt(highest)){
highest = Integer.toString(score);
} else {
}
}catch(IOException e){
}
bw.write(score);
bw.close();
}
The result I want from this is that when a player ends the game, the score would get recorded. If its a high score then it would be recorded in a scores.txt file. But my BufferedWriter refuses to write a file which results to the error mentioned.
The problem is that highest has not a valid integer value when you do Integer.parseInt(highest). Use debug options to see which value contains and fix that problem.

System.out.println prints the string but System.out.print does not

I am trying to store the words in a file separated by coma in a java array
The file is
Age,Income,Student,Credit Rating,Class: Buys Computer
Youth,high,No,Fair,No
Youth,high,No,Excellent,No
Middle aged,high,No,Excellent,No
Senior,medium,No,Fair,Yes
Senior,Low,Yes,Fair,Yes
Senior,Low,Yes,Excellent,No
public class Test {
public static void main(String args[]) throws FileNotFoundException, IOException{
FileInputStream f=new FileInputStream("F:\\pr\\src\\dmexam\\inp2.txt");
int size,nr=7,nc=5,j=0,i=0;
char ch;
String table[][]=new String[nr][nc];
size=f.available();
table[0][0]=new String();
while(size--!=0){
ch=(char)f.read();
if(ch=='\n')
{
i++;
if(i>=nr)
break;
table[i][0]=new String();
j=0;
continue;
}
if(ch==',')
{
j++;
table[i][j]=new String();
continue;
}
table[i][j]+=ch;
}
f.close();
System.out.println("The given table is:::---");
for(i=0;i<nr;i++){
for(j=0;j<nc;j++){
System.out.print(" "+table[i][j]);
System.out.print(" ");
}
}
}
}
But the output is
The given table is:::---
But if the for is changed like this
System.out.println("The given table is:::---");
for(i=0;i<nr;i++){
for(j=0;j<nc-1;j++){
System.out.print(" "+table[i][j]);
System.out.print(" ");
}
System.out.println(table[i][nc-1]);
}
The output is
The given table is:::---
Age Income Student Credit Rating Class: Buys Computer
Youth high No Fair No
Youth high No Excellent No
Middle aged high No Excellent No
Senior medium No Fair Yes
Senior Low Yes Fair Yes
Senior Low Yes Excellent No
I want to know "why System.out.print is not workig???"...
The PrintStream that System.out uses has an internal buffer, since writing to stdout is relatively expensive -- you wouldn't necessarily want to do it for each character. That buffer is automatically flushed when you write a newline, which is why println causes the text to appear. Without that newline, your string just sits in the buffer, waiting to get flushed.
You can force a manual flush by invoking System.out.flush().
Okay let me try to help you out here. So you are making your life really rough at the moment. Have you tried to look at different libraries like BufferedWritter/FileWritter?
You can easily import these into your project using:
import java.io.BufferedWritter;
import java.io.FileWritter;
It is also recommended to catch errors using the IOException library:
import java.io.IOException;
As for the separation of the words, these libraries give you tools like control over the delimiter. For example we can do something like this:
//this is if you are creating a new file, if not, you want true to append to an existing file
BufferedWriter bw = new BufferedWriter(new FileWriter("test.txt", boolean false));
try
{
// write the text string to the file
bw.write("Youth,high,No,Fair,No");
// creates a newline in the file
bw.newLine();
}
// handle exceptions
catch (IOException exc)
{
exc.printStackTrace();
}
// remember to close the file at the end
bw.close();
Now that is for hard coding the data, but we can do this with a for loop. We can add delimiters in the function within the for loop, for example: (I am not sure how you have the data stored, but I am assuming you save it in an array. I am also assuming there will ALWAYS be 5 sets of data per line)
BufferedWriter bw = new BufferedWriter(new FileWriter("test.txt", boolean false));
for (int i = 1, i <= listName.size()+1, i++) {
if (i % 5 == 0) {
bw.write(listName.get(i-1));
bw.write(", ");
bw.newLine();
} else {
bw.write(listName.get(i-1));
bw.write(", ");
}
}
This would write to the file:
Youth,high,No,Fair,No
Youth,high,No,Excellent,No
Middle aged,high,No,Excellent,No
Senior,medium,No,Fair,Yes
Senior,Low,Yes,Fair,Yes
Senior,Low,Yes,Excellent,No
This may make your life a little easier (if I am understanding your needs clearly). Next time please make sure to flesh out your question more than you did.
DISCLAIMER: I did not test all of the code, so if you find an error please let me know and I will edit it as needed. If I get time I will make sure it works.

Concatenate user input Strings to convert into a complete file path (Java)

I wrote a short script to create a file to my Desktop, and the file appeared. I just did it all in main, like so:
import java.io.*;
import java.util.Scanner;
public class FilePractice {
public static void main(String[] args) {
//create a new File object
File myFile = new File("/home/christopher/Desktop/myFile");
try{
System.out.println("Would you like to create a new file? Y or N: ");
Scanner input = new Scanner(System.in);
String choice = input.nextLine();
if(choice.equalsIgnoreCase("Y"))
{
myFile.createNewFile();
}
else
{
//do nothing
}
}catch(IOException e) {
System.out.println("Error while creating file " + e);
}
System.out.println("'myFile' " + myFile.getPath() + " created.");
}
}
I just wanted to make sure the code worked, which it did. After that, I wanted to expand by creating a file with user input, as well as define which directory the user wished to send the file to. I'm on a Linux machine, and I wanted to send it to my Desktop again, so my user input was "/home/christopher/Desktop" for the userPath. Nothing happened. I even cd'd to my Desktop via terminal to "ls" everything there, and still nothing.
Perhaps my syntax is wrong?
If this is a duplicate of anything, my apologies. I tried to do a thorough search before coming here, but I only found info on creating files and sending files to directories that are already defined as a string (e.g. File myFile = new File("/home/User/Desktop/myFileName")).
Here is the expanded attempt:
try {
System.out.println("Alright. You chose to create a new file.\nWhat would you like to name the file?");
String fileName = input.nextLine();
input.nextLine();
System.out.println("Please enter the directory where you would like to save this file.\nFor example: C:\\Users\\YourUserName\\Documents\\");
String userFilePath = input.nextLine();
File userFile = new File(userFilePath, fileName);
System.out.println("Is this the file path you wish to save to? ----> " + userFile.getPath()+"\nY or N: ");
String userChoice = input.nextLine();
if (userChoice.equalsIgnoreCase("Y")) {
userFile.createNewFile();
//print for debug
System.out.println(userFile.getPath());
}
}catch(IOException e) {
System.out.println("Error while attempting to create file " + e);
}
System.out.println("File created successfully");
My print statement for a debug attempt outputs "/home/christopher/Desktop", but not the file name appended to the directory.
Thanks for any help offered. This is just for experimentation while learning Java I/O. Since a hypothetical user may not be on the same OS as me, I can work on those methods later. I'm keeping it on my home machine, hence the Unix filepath names.
Changing input.nextLine() to input.next() solved the problem. The program was not reaching the if statement after asking the user if they were sure their entered path was the desired save point.
I also put in a simple else statement that printed out ("File not created") to verify that it was skipping it.
Anyway, question answered. :-)

Saving and Recalling data on java

Im new to programming, and I am making a code in which I record boolean data each day of the week to see if the user did the task that they are required to do.
For example:
Press 'y' if you went to soccer practice today.
Press 'n' if you didn't.
I need the program to be able to ask this for all five days of the week and in the end record the number of times they went to soccer practice in one month. I have the basic idea on how to make the code for something if the user was going to enter it in one opening. But I need to save that boolean data every single day, and then recall... any ideass.....thankx
You need to save the values to some persistent storage. The simplest is file. Other could be database. So you need to find out how to read/write from
Java allows you to create file objects and read and write to them which is what you need. Here is a basic example to help you get started:
import java.io.*
public class MyFileReaderWriter {
public static void main(String[] args) {
File myFile = new File("sample.txt");
try {
BufferedWriter w = new BufferedWriter(new FileWriter(myFile));
w.write(Integer.toString(1));
w.write(Integer.toString(0));
w.write("HELLO WORLD");
w.close();
BufferedReader r = new BufferedReader(new FileReader(myFile));
String s = r.readLine();
System.out.println(s);
r.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
If you can get hold of a static Map (collection) which will gets created only at the start of the program and add the data to the map at the end of each day.

Writing to a text file within a loop - JAVA

I've got a loop that reads through a text file and outputs it, now I'm trying to get it to loop through, and write what's printed out into a text file as I want it to display as HTML. This is what I've got so far for this method:
public void hChoice()
{
File fbScores = new File ("P:/SD/Assignment1/fbScores.txt");
String line = "";
try {
Scanner scanScores = new Scanner(fbScores);
while(scanScores.hasNext())
{
line = scanScores.nextLine();
stringArr = line.split(":");
if(stringArr.length == 4)
{
System.out.println("<h1>" + stringArr[0]+" [" +stringArr[2]+"] |" + stringArr[1]+" ["+ stringArr[3]+" ]<br></h1> ");
PrintWriter out = new PrintWriter("P:/SD/Assignment1/HTMLscores.txt");
out.close();
}
}
}
catch (FileNotFoundException e)
{
System.out.println("problem " +e.getMessage());
}
}
I've added the HTML tags in the print out and it prints it out fine, but I've tried several different methods to get it to print to a text file but none have worked. Pretty new to Java so any help would be much appreciated. Thankyou. :)
You've gotten your syntax and code wrong for writing to files.
Please Google and check the right syntax for writing to files using java. Plenty of resources available. You'll learn better if you try it yourself.
FYR, here is one: http://www.tutorialspoint.com/java/java_files_io.htm

Categories