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.
String.isEmpty
If you merely want to ignore blank lines, check the length of the line.
String line = scc.nextLine() ;
if ( ! line.isEmpty() ) { … } // Ignore any empty lines.
Array.length
Check all your inputs, including the number of fields in each line of incoming text.
String line = scc.nextLine() ;
if ( ! line.isEmpty() ) // Ignore any empty lines.
{
String[] parts = line.split( "\\|" );
if ( parts.length == 3 )
{
… handle valid input
}
else
{
… handle faulty input
}
}
In real work, I would scan each line, examining all code points, to verify that all characters are either a digit or the vertical bar character used here as a delimiter.
// Every character must be either a digit or a VERTICAL BAR.
// The code point for VERTICAL BAR (`|`) character is 124 (0x7C).
if ( line.codePoints().filter( codePoint -> ! ( Character.isDigit( codePoint ) || codePoint == 124 ) ).count() > 0L ) { … handle unexpected characters … }
FYI, Character.isDigit
checks for more digits than just ISO-LATIN-1 digits ('0' through '9'). So you may want to write more narrow test.