I've been programming Monopoly on java and I've been running into a NumberFormatException when I pull the rent values from a .txt file.
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
Here's the code:
try{
//Searching for .txt file
fileName = "N://java/Monopoly/src/rent.txt";
//creating FileReader and BuffReader objects
FileReader input = new FileReader(fileName);
BufferedReader bufRead = new BufferedReader(input);
//reading first line
String line = bufRead.readLine();
while(line!=""){
//not sure why, but program doesn't run well without if statement
if(line!=""){
//creating array of in variable
splitArr = line.split(",");
//creating rent object
rent r = new rent(Integer.parseInt(splitArr[0]),Integer.parseInt(splitArr[1]),Integer.parseInt(splitArr[2]),Integer.parseInt(splitArr[3]),Integer.parseInt(splitArr[4]),Integer.parseInt(splitArr[5]));
//storing rent object to a public static Arraylist holding all rents for the game
rents.add(r);
//debugging code that has been commented out
//System.out.println(r.toString());
}
//debugging code that has been commented out
/*for(String s : splitArr){
System.out.print(s+", ");
}*/
//reading next line
line = bufRead.readLine();
}
//closing IO stream
bufRead.close();
//preventing out of bounds exception error
}catch (ArrayIndexOutOfBoundsException e){
System.out.println("Usage: java ReadFile filename: rent\n");
//preventing IOException error
}catch (IOException e){
e.printStackTrace();
//I can't quite remember I have this in there. I know it didn't work right without it at some point
}catch(NullPointerException e){
}
When I uncomment the enhanced for loop at line 16, I get some values followed by the error and then all of the rest of the values as if there was no problem. I have noticed that when I delete and re-enter the values where the error begins, the error moves to other places. I've checked the arguments in the rent class (it requires 6 int's) and have checked the .txt file where all the values are good.
How do I fix this or should I not worry about it and add another catch statement to ignore the error?
You're comparing strings with !=. You should use !line.equals(""). – Saviour Self
Related
Goal of this assignment is to create a while loop that goes through file "flowers.dat" (I'll paste it later in this post) until the EoF is reached, then it should print a flowers name and if it'll grow in the shade or sun. Here's what I've got so far:
import java.io.*; // Import class for file input.
public class Flowers
{
public static void main(String args[]) throws Exception
{
// Declare variables here
String flowerName;
String sunOrShade;
File flower = new File("flowers.dat");
// Open input file.
// Create BufferedReader object.
BufferedReader reader;
// Write while loop that reads records from file.
while ((flowerName = reader.readLine()) != null) {
System.out.println(flowerName + "is grown in the " + sunOrShade);
}
// Print flower name and the words sun or shade.
flower.close();
System.exit(0);
} // End of main() method.
}
Here is the "flowers.dat". Here I noted that the Flower and sun/shade alternate, so it makes me think that I need to include a for loop in the while loop that alternates between each line, assigns one line to flowerName and the other to sunOrShade, then prints the line and it again until it reaches null.
Astilbe
Shade
Marigold
Sun
Begonia
Sun
Primrose
Shade
Cosmos
Sun
Dahlia
Sun
Geranium
Sun
Foxglove
Shade
Trillium
Shade
Pansy
Sun
Petunia
Sun
Daisy
Sun
Aster
Sun
Also, I'm getting this error message. I'm not sure why it doesn't close the .dat file
Flowers.java30: error : cannot find symbol
flower.close();
^
symbol: method close()
location: variable flower of type File
Error: could not find or load main class Flowers
The class File is just for the classpath, it is not about opening any stream. Not valid to call method close on the flower instance which is a File object.
flower is declared as a File object and there is no close() method for this object. You need to initialize your BufferedReader (reader)
BufferedReader reader = new BufferedReader(new FileReader(flower));
and close that since that is what will be accessing the file and reading it. It should be reader.close(). That should solve the particular error you mentioned. But take it a littler further so that you don't need close the reader and allow it to close itself when things are done or an Exception occurs by using Try With Resources when setting up the reader:
File flower = new File("flowers.dat");
try (BufferedReader reader = new BufferedReader(new FileReader(flower))) {
// Write while loop that reads records from file.
while ((flowerName = reader.readLine()) != null) {
//read in the next line to get the required lighting.
sunOrShade = reader.readLine();
System.out.println(flowerName + " is grown in the " + sunOrShade);
}
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}
And you don't need System.exit(0); to end the application. It will end when the main() method is finished.
I am writing code to process a list of tar.gz files, inside which there are multiple, csv files. I have encountered the error below
com.opencsv.exceptions.CsvMalformedLineException: Unterminated quoted field at end of CSV line. Beginning of lost text: [,,,,,,
]
at com.opencsv.CSVReader.primeNextRecord(CSVReader.java:245)
at com.opencsv.CSVReader.flexibleRead(CSVReader.java:598)
at com.opencsv.CSVReader.readNext(CSVReader.java:204)
at uk.ac.shef.inf.analysis.Test.readAllLines(Test.java:64)
at uk.ac.shef.inf.analysis.Test.main(Test.java:42)
And the code causing this problem is below, on line B.
public class Test {
public static void main(String[] args) {
try {
Path source = Paths.get("/home/xxxx/Work/data/amazon/labelled/small/Books_5.json.1.tar.gz");
InputStream fi = Files.newInputStream(source);
BufferedInputStream bi = new BufferedInputStream(fi);
GzipCompressorInputStream gzi = new GzipCompressorInputStream(bi);
TarArchiveInputStream ti = new TarArchiveInputStream(gzi);
CSVParser parser = new CSVParserBuilder().withStrictQuotes(true)
.withQuoteChar('"').withSeparator(',').
.withEscapeChar('|'). // Line A
build();
BufferedReader br = null;
ArchiveEntry entry;
entry = ti.getNextEntry();
while (entry != null) {
br = new BufferedReader(new InputStreamReader(ti)); // Read directly from tarInput
System.out.format("\n%s\t\t > %s", new Date(), entry.getName());
try{
CSVReader reader = new CSVReaderBuilder(br).withCSVParser(parser)
.build();
List<String[]> r = readAllLines(reader);
} catch (Exception ioe){
ioe.printStackTrace();
}
System.out.println(entry.getName());
entry=ti.getNextEntry(); // Line B
}
}catch (Exception e){
e.printStackTrace();
}
}
private static List<String[]> readAllLines(CSVReader reader) {
List<String[]> out = new ArrayList<>();
int line=0;
try{
String[] lineInArray = reader.readNext();
while(lineInArray!=null) {
//System.out.println(Arrays.asList(lineInArray));
out.add(lineInArray);
line++;
lineInArray=reader.readNext();
}
}catch (Exception e){
System.out.println(line);
e.printStackTrace();
}
System.out.println(out.size());
return out;
}
}
I also attach a screenshot of the actual line within the csv file that caused this problem here, look at line 5213. I also include a test tar.gz file here: https://drive.google.com/file/d/1qHfWiJItnE19-BFdbQ3s3Gek__VkoUqk/view?usp=sharing
While debugging, I have some questions.
I think the issue is the \ character in the data file (line 5213 above), which is the escape character in Java. I verified this idea by adding line A to my code above, and it works. However, obviously I don't want to hardcode this as there can be other characters in the data causing same issue. So my question 1 is: is there anyway to tell Java to ignore escape characters? Something like the opposite of withEscapeChar('|')? UPDATE: the answer is to use '\0', thanks to the first comment below.
When debugging, I notice that my program stops working on the next .csv file within the tar.gz file as soon as it hit the above exception. To explain what I mean, inside the tar.gz file included in the above link, there are two csvs: _10.csv and _110.csv. The problematic line is in _10.csv. When my program hit that line, an exception is thrown and the program moves on to the next file _110.csv (entry=ti.getNextEntry();). This file is actually fine, but the method readAllLines that is supposed to read this next csv file will throw the same exception immediately on the first line. I don't think my code is correct, especially the while loop: I suspect the input stream was still stuck at the previous position that caused the exception. But I don't know how to fix this. Help please?
using RFC4180Parser worked for me.
I'm trying to code for a file not found exception in a while loop so that the program continues prompting the user for the file (test.txt). I wrote a try/catch block inside a while loop. However, when I delete the input file (test.txt), the program should catch this error and print "Error, cannot locate the 'test.txt' file, please try again:" and allow the user to input another file name. However, the program crashes and gives me a FileNotFoundException.
In this case it's probably better to ask for permission rather than forgiveness (e.g. check if the file exists before attempting to read it).
File file = new File("test_input.txt");
if (file.exists()) {
FileReader fileReader = new FileReader(file);
}
You should add another try and catch for the Scanner
// prompt user for name for output textfile
System.out.println();
System.out.print("What would you like to call your output file: ");
String outputName = inputReader.nextLine();
// scanner and printwriter objects for reading text file
try {
Scanner in = new Scanner(correctInputfile);
PrintWriter out = new PrintWriter(outputName);
// read input (values) and write the output (average)
// messages triggered by successful location of files.
if (fileName.equalsIgnoreCase(("test_input.txt"))) {
// code logic
}
} catch (FileNotFoundException ex) {
System.out.println();
System.out.println("***** ERROR *****");
System.out.println("\nCannot locate the input file " + "'" + fileName + "'" + "on your computer - please try again.");
System.out.print("\nInput file name (from your computer): ");
}
In your code, two lines raise FileNotFoundExceptions that you are not catching:
// scanner and printwriter objects for reading text file
Scanner in = new Scanner(correctInputfile);
PrintWriter out = new PrintWriter(outputName);
// read input (values) and write the output (average)
You can replace them with the following, and the code (should) work.
Scanner in = null;// Initialize to null, so they don't raise warnings.
PrintWriter out = null;
try { // Surround with try/catch to get the exception
in = new Scanner(correctInputfile);
out = new PrintWriter(outputName);
}catch(FileNotFoundException e){
/*TODO: something about the exception here!
Make sure the Scanner and PrintWriter get
properly initialized with valid file names.*/
}
below here is my coding logic.
1st time user key in Name as "John" and address as "123", save in to
text file.
2nd time user key in exact value Name as "John" and address as
"123", it will throw error like "can't be exact value"
I Created text file first
try{
new JTextField();
// create new file
String path="C:\\export.txt";
File file = new File(path);
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
// write in file
if (txtName.getText() !=null && txtAddress.getText() !=null)
{
bw.write(txtName.getText());
bw.write(";");
bw.write(txtAddress.getText());
bw.write(System.getProperty("line.separator"));
System.out.print("Print Write Line :" +txtName.getText() +txtAddress.getText());
}else {
System.out.print(""");
}
// close connection
bw.flush();
bw.close();
fw.close();
}catch(Exception e){
System.out.println(e);
}
Then I created Read file and do checking for duplicated values
try{
BufferedReader in = new BufferedReader(new FileReader("C:\\Users\\minzan\\Desktop\\export.txt"));
String line;
while ((line = in.readLine()) != null) {
//read all the line from the text file
System.out.println("Print Read line :" +line);
}
if((txtName.getText().compareTo(line)==0) && (txtAddress.getText().compareTo(line)==0))
{
//read the output line first
//if o , it is a match and thwor error
System.out.println("Error : Same Name and Address :");
}
in.close();
}catch(Exception e){
System.out.println("Error : Same Name and Address");
}
This is the output when i type 1st time key in, it straight throw error:
Print Write Line :John123
Print Read line :John;123
Error : Same Name and Address
A couple of things I notice is that in your validation code that checks for duplicate values, you will always compare the input with the very last line in the file. Also, you are assuming that if an exception is thrown that it means that the name and address are the same. Since you're not checking to see if the file exists, I am guessing that you're getting a FileNotFoundException that is being thrown when you try to read a file that doesn't exists. Given that the path in your writer is different than the file in your validation code, I am going to bet that this is it. :)
Let's read it in english :)
Keep printing the line until line becomes null.
compare name and address to null - NullPointerException!
You probably haven't learn about Set yet but you should at least know about array and for loop. Use those to solve your problem. Use lots of System.out.println() if the program is not doing what you tell it to.
I want to get multiple file by parsing a input file Through Java.
The Input file contains many fasta format of thousands of protein sequence and I want to generate raw format(i.e., without any comma semicolon and without any extra symbol like ">", "[", "]" etc) of each protein sequence.
A fasta sequence starts form ">" symbol followed by description of protein and then sequence of protein.
For example ► >lcl|NC_000001.10_cdsid_XP_003403591.1 [gene=LOC100652771]
[protein=hypothetical protein LOC100652771] [protein_id=XP_003403591.1] [location=join(12190..12227,12595..12721,13403..13639)]
MSESINFSHNLGQLLSPPRCVVMPGMPFPSIRSPELQKTTADLDHTLVSVPSVAESLHHPEITFLTAFCL
PSFTRSRPLPDRQLHHCLALCPSFALPAGDGVCHGPGLQGSCYKGETQESVESRVLPGPRHRH
Like above formate the input file contains 1000s of protein sequence. I have to generate thousands of raw file containing only individual protein sequence without any special symbol or gaps.
I have developed the code for it in Java but out put is : Cannot open a file followed by cannot find file.
Please help me to solve my problem.
Regards
Vijay Kumar Garg
Varanasi
Bharat (India)
The code is
/*Java code to convert FASTA format to a raw format*/
import java.io.*;
import java.util.*;
import java.util.regex.*;
import java.io.FileInputStream;
// java package for using regular expression
public class Arrayren
{
public static void main(String args[]) throws IOException
{
String a[]=new String[1000];
String b[][] =new String[1000][1000];
/*open the id file*/
try
{
File f = new File ("input.txt");
//opening the text document containing genbank ids
FileInputStream fis = new FileInputStream("input.txt");
//Reading the file contents through inputstream
BufferedInputStream bis = new BufferedInputStream(fis);
// Writing the contents to a buffered stream
DataInputStream dis = new DataInputStream(bis);
//Method for reading Java Standard data types
String inputline;
String line;
String separator = System.getProperty("line.separator");
// reads a line till next line operator is found
int i=0;
while ((inputline=dis.readLine()) != null)
{
i++;
a[i]=inputline;
a[i]=a[i].replaceAll(separator,"");
//replaces unwanted patterns like /n with space
a[i]=a[i].trim();
// trims out if any space is available
a[i]=a[i]+".txt";
//takes the file name into an array
try
// to handle run time error
/*take the sequence in to an array*/
{
BufferedReader in = new BufferedReader (new FileReader(a[i]));
String inline = null;
int j=0;
while((inline=in.readLine()) != null)
{
j++;
b[i][j]=inline;
Pattern q=Pattern.compile(">");
//Compiling the regular expression
Matcher n=q.matcher(inline);
//creates the matcher for the above pattern
if(n.find())
{
/*appending the comment line*/
b[i][j]=b[i][j].replaceAll(">gi","");
//identify the pattern and replace it with a space
b[i][j]=b[i][j].replaceAll("[a-zA-Z]","");
b[i][j]=b[i][j].replaceAll("|","");
b[i][j]=b[i][j].replaceAll("\\d{1,15}","");
b[i][j]=b[i][j].replaceAll(".","");
b[i][j]=b[i][j].replaceAll("_","");
b[i][j]=b[i][j].replaceAll("\\(","");
b[i][j]=b[i][j].replaceAll("\\)","");
}
/*printing the sequence in to a text file*/
b[i][j]=b[i][j].replaceAll(separator,"");
b[i][j]=b[i][j].trim();
// trims out if any space is available
File create = new File(inputline+"R.txt");
try
{
if(!create.exists())
{
create.createNewFile();
// creates a new file
}
else
{
System.out.println("file already exists");
}
}
catch(IOException e)
// to catch the exception and print the error if cannot open a file
{
System.err.println("cannot create a file");
}
BufferedWriter outt = new BufferedWriter(new FileWriter(inputline+"R.txt", true));
outt.write(b[i][j]);
// printing the contents to a text file
outt.close();
// closing the text file
System.out.println(b[i][j]);
}
}
catch(Exception e)
{
System.out.println("cannot open a file");
}
}
}
catch(Exception ex)
// catch the exception and prints the error if cannot find file
{
System.out.println("cannot find file ");
}
}
}
If you provide me correct it will be much easier to understand.
This code will not win prices, due to missing java expertice. For instance I would expect OutOfMemory even if it is correct.
Best would be a rewrite. Nevertheless we all began small.
Give full path to file. Also on the output the directory is probably missing from the file.
Better use BufferedReader etc. i.o. DateInputStream.
Initialize i with -1. Better use for (int i = 0; i < a.length; ++i).
Best compile the Pattern outside the loop. But remove the Matcher. You can do if (s.contains(">") as well.
. One does not need to create a new file.
Code:
const String encoding = "Windows-1252"; // Or "UTF-8" or leave away.
File f = new File("C:/input.txt");
BufferedReader dis = new BufferedReader(new InputStreamReader(
new FileInputStream(f), encoding));
...
int i= -1; // So i++ starts with 0.
while ((inputline=dis.readLine()) != null)
{
i++;
a[i]=inputline.trim();
//replaces unwanted patterns like /n with space
// Not needed a[i]=a[i].replaceAll(separator,"");
Your code contains the following two catch blocks:
catch(Exception e)
{
System.out.println("cannot open a file");
}
catch(Exception ex)
// catch the exception and prints the error if cannot find file
{
System.out.println("cannot find file ");
}
Both of these swallow the exception and print a generic "it didn't work" message, which tells you that the catch block was entered, but nothing more than that.
Exceptions often contain useful information that would help you track down where the real problem is. By ignoring them, you're making it much harder to diagnose your problem. Worse still, you're catching Exception, which is the superclass of a lot of exceptions, so these catch blocks are catching lots of different types of exceptions and ignoring them all.
The simplest way to get information out of an exception is to call its printStackTrace() method, which prints the exception type, exception message and stack trace. Add a call to this within both of these catch blocks, and that will help you see more clearly what exception is being thrown and from where.