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.
Related
public static void Replace_Record(String editTerm, String newItem, String newAmount, String newPrice){
String filepath="temp_Food_Item.txt";
String tempfile= "temp_Food_Item_temp.txt";
File oldFile= new File(filepath);
File newFile=new File(tempfile);
String item=""; String quantity=""; String price="";
System.out.println("working ");
try{
//System.out.println("working pt1");
FileWriter fw= new FileWriter(tempfile,true);
BufferedWriter bw= new BufferedWriter(fw);
PrintWriter pw= new PrintWriter(bw);
x = new Scanner(new File(filepath));
x.useDelimiter("[,/n]");
//System.out.println("working pt2");
while(x.hasNext()){
//System.out.println("working pt3");
item=x.next();
quantity=x.next();
price=x.next();
if(item.equalsIgnoreCase(editTerm)){
pw.println(newItem+","+newAmount+","+newPrice);
}
else{
//System.out.println("working pt4 ");
pw.println(item+","+quantity+","+price);
}
}
x.close();
pw.flush();
pw.close();
oldFile.delete();
File dump=new File(filepath);
newFile.renameTo(dump);
}
catch(Exception e){
System.out.println("Error declared");
}
}
I don't understand where I went wrong but it is printing "error declared" so I debugged and found after working pt1 it stops and goes to catch please help?
Additional info includes:
I am making a database for a restaurant and I am inputting info in txt files in the sequence item_name,item_amount,item_price so I am taking my new values from, main and passing them to the method, in theory, it first duplicates a file until it comes to the strings I wanna remove and then replaces them and goes back to copy the strings from the real files. but every time I run this I get catch.
TIA
While I can't answer your question straight away, I can offer a few ideas.
First of, catch a more explicit exception, such as IOException, FileNotFoundException. It is generally good practice to have more explicit code and it's the first step towards improved error handling.
Also do something with it, for startes you can print it in your console and use that information to debug your program. It might tell you exactly what your error is and where it is.
hello everyone thanks for helping me through this problem but I have managed to fix it I took your tips and ran multiple types of exception till I found this was a file io error and I had a problem about naming the files so the compiler could not recognize which file I was calling other than that we Gucci thank you guys
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) {
}
}
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.
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.
I am working through an assignment and have run into a few snags.
My program prints output to the screen, (not how I need it yet) but only prints the first entry to the file. Below is a snippet of the code. The file appears to be reading in the data from the input file, but the loop does not output to the file past the first entry.
Scanner in = new Scanner(System.in); //Scanner object to read input from the file
System.out.println("Enter filename to read "); //file name prompt
String inputFileName = in.nextLine(); //line input reads next line
/*
* TODO 2) Use an unbuffered file input stream to open listings.txt file
* and read in property listings.
*/
Scanner reader = null;
try {
reader = new Scanner(new File(inputFileName));
} catch (FileNotFoundException e) {
System.out.println("Try Again"); //error window if name is null
JOptionPane.showMessageDialog(null, "You must enter a filename", "File input error", JOptionPane.ERROR_MESSAGE);
return;
}
PrintWriter out = new PrintWriter("agentreport.txt"); //This method prints out the file readfile.txt a word at a time
while (reader.hasNextLine()) { //It needs to output to the text file. Currently a file is created, but it is empty?
Scanner s2 = new Scanner(reader.next());
#SuppressWarnings("unused")
boolean b;
while (b = s2.hasNext()) {
String output = s2.next();
String output2 = output.toUpperCase(); //converts output to upper case
System.out.println(output2);
out.print(output2); //only printing the first entry to the agentsreport.txt file. Not stepping thru the file for some reason?
}
Even if you are using automatic flushing, which you aren't in this case, the PrintWriter object would output anything in its internal buffer unless you do one of two things:
1) Use the println(), printf(), or format() to methods
2) Make a call to the flush() method every time you print, this way all of the data in the internal buffer gets written out.
Note: The print() method does not cause the PrintWriter object to flush() its buffer.
try adding a call to flush() after you call print()
Example of split()
PrintWriter out = new PrintWriter("agentreport.txt");
while (reader.hasNextLine()) {
String words = reader.nextLine().split();
#SuppressWarnings("unused")
boolean b;
for(String word : words) {
String output = word ;
String output2 = output.toUpperCase(); //converts output to upper case
System.out.println(output2);
out.print(output2);
}
One thing that immediately jumps out is that you aren't handling your resources properly.
Any time you use an IO resource such as a reader/database connection/etc., you should always close it using a finally block, using this sort of pattern:
Reader reader = /* construct it however */
try {
/* do something with the reader */
}
finally {
reader.close();
}
If you don't do this, there's no guarantee that the reader will actually be closed, and your application will leak file descriptors/connection pool connections/etc., until eventually it won't be able to get hold of any more and your app crashes. (This won't always have fatal consequences, but it's such a straightforward pattern you should use it every time until it becomes automatic).
In this case, you aren't closing your writer at all, which means that it's not guaranteed that it ever actually flushes its output to the file. It would be perfectly in accordance with the Writer interface for it to write everything or nothing - without the flush, you have no guarantees. Note that closing the writer will automatically call flush, so that's the best bet once you're done with it.
So the latter part of your code should look like:
PrintWriter out = new PrintWriter("agentreport.txt");
try {
// Existing code here
}
finally {
// This closes the file and frees the descriptor, but also flushes the buffers
out.close();
}
Also, how are you handling the IOExceptions that can be thrown by the reading and writing? Are you catching them and swallowing them somewhere? If so, it's possible that your code is throwing an exception telling you exactly why it can't write, and you're just ignoring it and then looking puzzled.
Not to put too fine a point on it, error handling is probably the most significant part of good software development. It's not too hard to write software that works when everything's fine; the most challenging part is handling things well when you run out of space on the hard drive, or the network is temporarily down, etc.
In this case the most pragmatic approach would be to just let the exception be thrown out of the top of your main method. In this case your application will "crash", and you'll get a stacktrace + error message on the console, which will make it immediately clear that something went wrong, and give you a very good idea of what it was.
try
out.println(output2);
http://docs.oracle.com/javase/6/docs/api/java/io/PrintWriter.html
also I'd use a var other than "out" as when system.out is imported to use the shortcode 'out.println()', this could cause variable confusion
edit: good point #Hunter McMillen, changed to println as append is for a CharSequence.
try (
Scanner reader = new Scanner(new File(inputFileName));
PrintWriter writer = new PrintWriter(new FileOutputStream("agentreport.txt"), true);
) {
while (reader.hasNextLine()) {
String output = reader.nextLine().toUpperCase();
System.out.println(output);
writer.println(output);
}
} catch (FileNotFoundException e) {
System.out.println("Try Again"); //error window if name is null
JOptionPane.showMessageDialog(null, "You must enter a filename", "File input error", JOptionPane.ERROR_MESSAGE);
}