NumberFormatException being thrown by Integer.parseInt() - java

For my assignment, I'm trying to read a sequence of integers into an array and calculate a few things about the array. I'm restricted to using InputStreamReader and BufferedReader to read from the file, and Integer.parseInt() is throwing NumberFormatException after the first line read.
Everything works if I input each number individually by keyboard, but it doesn't work at all if I try and read directly from the file.
Here's the code so far
int[] array = new int[20];
try {
int x, count = 0;
do{
x = Integer.parseInt((new BufferedReader(new InputStreamReader(System.in)).readLine()));
array[count] = x;
count++;
}
while (x != 0);
}
catch (IOException e){
System.out.println(e);
}
catch (NumberFormatException e){
System.out.println(e);
}
The case to be tested is
33
-55
-44
12312
2778
-3
-2
53211
-1
44
0
When I try and copy/paste the whole test case, the program only reads the first line and then throws
NumberFormatException. Why does readLine() only read the first value and ignore everything else?s

You are reopening System.in each time. I don't know what this does but I assume it can't be good.
Instead, you should use one BufferedReader, and in your loop, read lines one by one from it.

The way that I think this is happening is that you create a reader, read one line, and then on the next iteration you create a new one, which is empty but still tries to read, therefore it reads "", passes it to the parser and Integer.parseInt() throws NumberFormatException because it can't be parsed. The correct way to do this is:
int[] array = new int[20];
try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
int x, count = 0;
do {
String s = reader.readLine();
x = Integer.parseInt(s);
array[count] = x;
count++;
}
while (x != 0);
} catch (IOException | NumberFormatException e) {
e.printStackTrace();
}

Related

Java parseInteger throwing error

I have the following code snippet from my tester class.
FileReader freader=new FileReader(filename);
BufferedReader inputFile=new BufferedReader(freader);
int numScores = 0;
String playerType = "";
String nameHome = "";
String playerName = "";
String home = "";
String location = "";
int score = 0;
String date = "";
double courseRating = 0;
int courseSlope = 0;
ArrayList<Player> players = new ArrayList<Player>();
while (inputFile.read()!= -1) {
numScores = Integer.parseInt(inputFile.readLine());
playerType = inputFile.readLine();
nameHome = inputFile.readLine();
StringTokenizer st = new StringTokenizer(nameHome,",");
playerName = st.nextToken();
home = st.nextToken();
The program compiles, however when the tester is run, I get the following output error.
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
at PlayerTest.main(PlayerTest.java:34)
I've tried researching this and what I fould was there's possibly a space when it changes the String that is read from the data file and converts it to an int. I tried reading directly into a strin, trimming the string, then converting to the int, but it got the same error.
This was the code that replaced numScores = Integer.parseInt(inputFile.readLine());
tempScores = inputFile.readLine();
tempScores.trim();
System.out.println(tempScores);
numScores = Integer.parseInt(tempScores);
Any help is appreciated.
*edited to show sample data
Sample data from file
3
B
James Smith, Strikers
FWB Bowling, 112,09/22/2012
White Sands, 142,09/24/2012
Cordova Lanes,203,09/24/2012
Possibly, your File contains empty lines. These are read as "" and therefore cannot be converted to int.
Furthermore, it is possible that you read the first character of each line by the read-statement in the header of the while-loop, so that it is ignored in the readline command. Then a number of length 1 (like "1") would become an empty line.
In any case, the construction of your loop is a bug.
You can put it all in an if statement:
if(!tempScores.equalsIgnoreCase(""))
{
I ran into a similar issue today. I was reading a response from REST end point and try to parse the json response. Bam! hit an error. Later on I realize the file had a BOM.
My suggestion is create a var
String var = inputFile.readLine();
int numScores = Integer.parseInt(var);
add a breakpoint and inspect what var contains, in my case the response had a BOM an empty unicode character code 65279 / 0xfeff. In any debugger worth it's salt you should be able to see each character.
if it's the case you need to strip that value from the string.
I used this library to detect this issue org.yaml:snakeyaml:1.16
import org.yaml.snakeyaml.reader.UnicodeReader;
//more code
private String readStream(InputStream inputStream) throws IOException {
UnicodeReader unicodeReader = new UnicodeReader(inputStream);
char[] charBuffer = new char[BUFFER_SIZE];
int read;
StringBuilder buffer = new StringBuilder(BUFFER_SIZE);
while ((read = unicodeReader.read(charBuffer,0,BUFFER_SIZE)) != -1) {
buffer.append(charBuffer, 0, read);
}
return buffer.toString();
}
You need to understand this please look into it.
Basic understanding is
try {
//Something that can throw an exception.
} catch (Exception e) {
// To do whatever when the exception is caught.
}
There is also an finally block which will always be execute even if there is an error. it is used like this
try {
//Something that can throw an exception.
} catch (Exception e) {
// To do whatever when the exception is caught & the returned.
} finally {
// This will always execute if there is an exception or no exception.
}
In your particular case you can have the following exceptions (link).
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException - if input is exhausted
IllegalStateException - if this scanner is closed
So you would need to catch exceptions like
try {
rows=scan.nextInt();
} catch (InputMismatchException e) {
// When the InputMismatchException is caught.
System.out.println("The next token does not match the Integer regular expression, or is out of range");
} catch (NoSuchElementException e) {
// When the NoSuchElementException is caught.
System.out.println("Input is exhausted");
} catch (IllegalStateException e) {
// When the IllegalStateException is caught.
System.out.println("Scanner is close");
}

Check if large list of words has specific length

I have a dictionary text file of around 60000 words. I would like to read in that text file and see if it has a certain amount of n words, provided by the user. At the recommendation of my Professor, I'm going to create a method that expands the array to compensate the different n values. I know how to do that. My question is, how do I initially read the text file and determine if each of the 60000 words has a specific n length?
I know I have to use a loop and import the file: (although I've never done throw exception)
Scanner inputFile = new Scanner(new File("2of12inf.txt"));
for(int i = 0; i < sizeWord; i++) {
}
But what I would normally do is use a charAt(i) , and check if the word has n many characters. But I can't possibly do that for 60000 words. Suggestions?
try{
BufferedReader br = new BufferedReader(new FileReader(new File("2of12inf.txt")));
String line;
while ((line = br.readLine()) != null) {
// process the line.
int lineLength = line.length();
// assuming each line contains one word, do whatever you want to with this length
}
} catch (Exception e) {
System.out.println("Exception caught! Should handle it accordingly: " + e);
} finally {
be.close();
}

InputStreamReader and reading random lines from .txt file

I have a method for my app to read a random line from a text file and return it. Im using the randTxt() to read and return a random line from the txt file.
but it only shows the same line (1st line) everytime.
public String randTxt(){
// Read in the file into a list of strings
InputStreamReader inputStream = new InputStreamReader(getResources().openRawResource(R.raw.randomstuff));
//ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
String theLine="";
int i;
try {
i = inputStream.read();
while (i != -1) {
i = inputStream.read();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
LineNumberReader rdr = new LineNumberReader(inputStream);
int numLines = 30;
Random r = new Random();
rdr.setLineNumber(r.nextInt(numLines));
try {
theLine = rdr.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return theLine;
}
How can I fix it? and Can someone explain what's wrong in my code?
Here's the framework for doing what you need using BufferedReader. In this case, you don't need to store the values in a temp array.
InputStreamReader inputStream = new InputStreamReader
(getResources().openRawResource(R.raw.randomstuff));
BufferedReader br = new BufferedReader(inputStream);
int numLines = 30;
Random r = new Random();
int desiredLine = r.nextInt(numLines);
String theLine="";
int lineCtr = 0;
while ((theLine = br.readLine()) != null) {
if (lineCtr == desiredLine) {
break;
}
lineCtr++;
}
...
Log.d(TAG, "Magic line is: " +theLine);
You have gotten an answer of how to fix your code, but no explanation of why our original code did not work.
LineNumberReader.setLineNumber(int) does not go to the actual line, it just changes what number you call the current line.
So, say you read two lines, getLineNumber() will now return 2 (it started at 0 and increased by 1 each time a newline was encountered). if you now setLineNumber(10), getLineNumber() will return 10. Reading yet another line (your third) will cause getLineNumber() to return 11.
This is described in the Java Doc.
inputStream.read does not return a line number. it returns the byte that was read. this isn't how you would read line by line. to read line by line, you should use buffered reader's readLine method. its probably easier at that point to read it all into a local array and use that array to randomly get an entry, rather than using a line number reader.
I think Random() function returns a value between 0 and 1. hence, you may have to multiply it with 100 to get an integer value. May even consider a MOD "your upper limit" operation to guarentee that the index you finally get is between 0 and your upper limit
Use the index you calculated thus, in your setLineNumber() method.
Edit:
As john said, we can get whole number using Random() object.
public String getRandomLine(String fileLoc) throws IOException
{
BufferedReader reader = new BufferedReader(new FileReader(fileLoc));
ArrayList<String> lines = new ArrayList<String>();
String line =null;
while( (line = reader.readLine())!= null )
lines.add(line);
// Choose a random one from the list
return lines.get(new Random().nextInt(lines.size()));
}
public String getRandomLineOpt(String fileLoc)throws IOException
{
File f=new File(fileLoc);
RandomAccessFile rcf=new RandomAccessFile(f, "r");
long rand = (long)(new Random().nextDouble()*f.length());
rcf.seek(rand);
rcf.readLine();
return rcf.readLine();
}

DataInputStream for input text files?

I am learning to read and write in Java and am stuck with a simple exercise. The program reads from 2 txt files that each contain numbers in rows. It writes to an output file the result of the multiplication of each row of numbers. eg. file 1 row 1 : 10, file 2 row 1: 2 , the program should write 20 to the output file. My code seems to have something missing somewhere. The output file is created but nothing is written to it. Any ideas?
import java.io.*;
import java.util.*;
class ReadWriteData
{
public static void main(String[] args) throws Exception
{
//create ouput file
PrintWriter output = new PrintWriter("output2.txt");
DataInputStream file1 = new DataInputStream(new FileInputStream(args[0]));
DataInputStream file2 = new DataInputStream(new FileInputStream(args[1]));
try
{
// read data from file
while (true)
{
double number1 = file1.readDouble();
double number2 = file2.readDouble();
double result = number1 * number2 ;
output.println(result);
}
}
catch (IOException e)
{
System.err.println("Error");
System.exit(1);
}
output.close() ;
}
}
Here is an implementation with a BufferedReader that works.
public static void main(String[] args) throws Exception {
//create ouput file
PrintWriter output = new PrintWriter("output2.txt");
BufferedReader file1 = new BufferedReader(new FileReader("numbers1.txt"));
BufferedReader file2 = new BufferedReader(new FileReader("numbers2.txt"));
try {
// read data from file
while (true) {
String number1AsString = file1.readLine();
String number2AsString = file2.readLine();
if (number1AsString == null || number2AsString == null) {
break;
}
double number1 = Double.parseDouble(number1AsString);
double number2 = Double.parseDouble(number2AsString);
double result = number1 * number2;
System.out.println("result:" + result);
output.println(result);
}
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
output.close();
file1.close();
file2.close();
}
}
Edit: Also you may want to modularize your code for instance creating a method that help reduce duplicated code. Also you may be interested to look for NumberFormatException in case any number is not properly formatted or includes letters for example.
private double readDoubleFromFile(BufferedReader file) throws IOException {
String numberAsString = file.readLine();
if (numberAsString == null) {
throw new IOException();
}
double number = Double.parseDouble(numberAsString);
return number;
}
The DataInputStream class is not for reading text files. it can only be used to read what DataOutput writes. If you have rows of human-readable numbers, you need to use an InputStreamReader and then parse the resulting streams with things like Double.parseDouble
Maybe you want to use a BufferedReader for this.
BufferedReader in = new BufferedReader(
new FileReader(args[0]));
Then:
String num = null;
while((num = in.readLine()) != null){
double d = Double.parseDouble(num);
//now you have a double value
}
This way you do not depend on the exception to indicate the end of file.
You need to call output.flush just before closing the stream. Also, you should close the streams to the files in a finally block, this will make sure that the close command wil always be executed.
The DataInputStream class reads from a binary file (or other source such as socket). This means that it is going to be completely misinterpreting those input text files, with possibly amusing (or very irritating) results. To read numbers from a text file, you should use a BufferedReader wrapping an InputStreamReader to read lines and then convert those to numbers with suitable parsing methods (e.g., Double.parseDouble if you're wanting to produce a floating-point number).
When testing these things, it's often helpful to put in some debugging output inside the loop that prints out each value as you read it. Like that, you can see if things have got stuck in some unexpected way.
With this while (true) without a break your code is basically running in an infinite loop and never stopping unless there's an exception.
If it did terminate but you didn't see an exception, then it might be caused by calling System.exit(1) in the catch. It might be too late then to print "Error" anyway (the stdout might have been abrupted too early) and the file will never be flushed/closed. Remove that System.exit(1) line.
Also, closing is supposed to happen in finally block. And best is to not print some nothing-saying message on exception but just let them go. Since you already have a throws Exception on the method, just remove the entire catch. Only use it when you can handle exceptions in a sensible manner.
PrintWriter output = new PrintWriter("output2.txt");
try {
output.println("something");
} finally {
output.close();
}
After
output.println(result);
add
output.flush();

Problem with buffered File Reader

I have been asked to write a file reader method, I have done one which works fine but cant get the 2nd one to work and keep getting this error after i open the booms.txt file
Error:java.util.NoSuchElementException
public instance variable
public List booms;
Code I'm using for the file reader
try
{
int x;
int y;
double boomTime;
boolean isAHit;
Scanner lineScanner;
bufferedFileReader = new BufferedReader(new FileReader(aFile));
String currentLine = bufferedFileReader.readLine();
while (currentLine != null)
{
lineScanner = new Scanner(currentLine);
lineScanner.useDelimiter(",");
x = lineScanner.nextInt();
y = lineScanner.nextInt();
boomTime = lineScanner.nextDouble();
isAHit = lineScanner.nextBoolean();
booms.add(new Boom(x,y,boomTime));
currentLine = bufferedFileReader.readLine();
}
}
catch (Exception anException)
{
System.out.println("Error:"+anException);
}
finally
{
try
{
bufferedFileReader.close();
}
catch (Exception anException)
{
System.out.println("Error:" +anException);
}
}
}
Please Help
Perhaps a blank line at the end of the file?
as maurice says, probably a blank or incorrect line of data in the file.
the exception (although you haven't posted the stack trace) is being thrown by the Scanner.next... calls.
Scanner.nextInt
NoSuchElementException - if input is
exhausted
this would be far more obvious to you and the members of this forum if you'd included the stack trace. try putting anException.printStackTrace(); in your catch blocks next time.
I'm using a another method that's not that complicated. just do this:
Scanner diskScanner = new Scanner(new File("pathname"));
to read for example a Integer from the specified file just type
int blahblahblah = diskScanner.nextInt();
Got it sorted I had a boolean variable which wasn't in the file it was reading :), its all about taking a break and looking at it again.

Categories