I have a text document with an list of numbers experated by “|”.
Ex:
0|0|2
1|0|1
1|1|0
2|0|1
2|1|0
2|2|1
3|0|0
3|1|1
3|2|0
3|3|1
I am generating this though code and all ways have an extra line at the bottom. I know i will always have this line and have writen my code accordingly, with a -1 value when creating an int array. The problem is when i have two lines instead of one after editing the file. outside of going into the file to remove the extra line i wanted the code to be able to ignore this problem.
my current code which works with no extra line:
while(scc.hasNextLine()){
String[] temp = scc.nextLine().split("\|");
for(int j = 0; j < 3; j++){
arr[points][j] = Integer.parseInt(temp[j]);
}
points++;
}
scc.close();
This works and gives no exceptions while only one line is at the bottom. but when there are two I have “NumberFormatException” from having a blank line with no ints on it.
I cant share all of my code as its very large and uses multiple custom functions. thank you for any assistence you can provide.
I tried to catch the excpetion using the following:
while(scc.hasNextLine()){
String[] temp = scc.nextLine().split("\|");
for(int j = 0; j < 3; j++){
try{
arr[points][j] = Integer.parseInt(temp[j]);
}
catch (NumberFormatException ignore){}
}
points++;
}
scc.close();
this generated a new error of “ArrayIndexOutOfBoundsException” when ignore both my output becomes only one line of code instead of a list of numbers.
thanks for all your help I think i figured out why my code had the second issue. you guys helped with the first.
George Volz is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2
String.isEmpty
If you merely want to ignore blank lines, check the length of the line.
String line = scc.nextLine() ;
if ( ! line.isEmpty() ) { … }
Array.length
Check all your inputs, including the number of fields in each line of incoming text.
String line = scc.nextLine() ;
if ( ! line.isEmpty() )
{
String[] parts = line.split( "\|" );
if ( parts.length == 3 )
{
… handle valid input
}
else
{
… handle faulty input
}
}
In real work, I would first scan the file, examine all code points, to verify that all characters are only digits, vertical pipe, or newlines.
1