Try/Catch error exception returing null [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I'm trying to read in a list of words a file using BufferedReader and determine if any are duplicates, and if they are, to not print them. I know that there is a SuperClass called "UniqueLineReader" that can check the occurrence of duplicate lines for you, and something else called Linked HashSet. However, I haven't learned either of these in class, so I'm trying not to use them.
Anyways, the e.getMessage() is printing "null", which I don't understand, because the file obviously isn't and I'm checking that it isn't. Do I have wrong placement of variables?
try {
inFile = new BufferedReader(new FileReader(inputName));
outFile = new PrintWriter(new FileWriter(outputName));
while((nextLine = inFile.readLine())!= null){
if(indexOf(nextLine) == -1){
insert(nextLine);
outFile.println(nextLine);}
else{
System.out.println(nextLine + " has been seen before!");
}
}
inFile.close();
}//try
catch(Exception e){
System.out.println(e.getMessage());
}//catch
My indexOf method:
private int indexOf(String newWord){
for(int i = 0; i < numWords; i++){
if(arrayStrings[i].equals(newWord)){
return i;
}
}
return -1;
}//indexOf
stacktrace
`java.lang.NullPointerException
at A2Q2.indexOf(A2Q2.java:58)
at A2Q2.removeDuplicateLines(A2Q2.java:79)
at TestA2Q2.main(TestA2Q2.java:10)

According to the stack trace, the problem is at line 58 of file A2Q2.java, at that line you are using this:
arrayStrings[i].equals(...)
Which means that either arrayStrings is null, or arrayStrings[i] is null.
Adding a simple System.out.println before that line (or using a debugger) will show you exactly what is wrong.
BTW: I see you are using a fixed size array instead of an ArrayList to save the lines, I recommend the latter in this case as you don't need to specify the maximum number of lines beforehand.

Related

Null Array Pointer [duplicate]

This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 4 years ago.
I am reading a string from a file, and parse the string and the different elements into an array for later manipulation.
Every thing works fine, however when printing elements inside the WHILE loop it works, however, when I try to print the array out of the while loop I get an array Null pointer.
Here is the code :
public PointsEX2(){
String temp = new String();
String[] parse =null;
File file = new File("C:/Users/DjKidoo/Desktop/IA/mof.txt");
Scanner sc = null;
for(int t=0;t<pt_tab1.length;t++){
pt_tab1[t]=new PointEX2();
}
try {
sc = new Scanner(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int j=0;
while ((sc.hasNextLine())&& (j<= pt_tab1.length)) {
temp = sc.next();
parse = temp.split(",",0);
pt_tab1[j]= new
PointEX2(Float.parseFloat(parse[0]),Float.parseFloat(parse[1]),Float.parseFloat(parse[2]),Float.parseFloat(parse[3]),parse[4]);
System.out.println(toString(pt_tab1[j])); // perfectly works
}
for (int i=0;i<pt_tab1.length;i++)
System.out.println(pt_tab1[i].x); // Array Null Pointer
}
You never increment j within your while loop, so it remains 0 and so you continually assign a new PointEX2 into the same array item, pt_tab1[0]. All the others are null.
pt_tab1 shouldn't even be an array but rather an ArrayList<PointEX2>, and then you wouldn't have this problem.

Is there a more efficient way in Java to read numbers from a file? [duplicate]

This question already has answers here:
Quickly read the last line of a text file?
(10 answers)
Closed 7 years ago.
I have a simple output text file, it is called logOutput.txt :
2
3
4
And I want my Java Program to give the most recent one in the file ( 4 ). Here is my code:
import java.util.*;
import java.io.*;
public class readLogFile {
public static void main(String[] a) {
int logNumber = 0;
try {
File file = new File("logOutput.txt");
Scanner input = new Scanner(file);
while (input.hasNext()) {
logNumber = input.nextInt();
}
System.out.println("the log # is: " + logNumber);
} catch (FileNotFoundException fne) {
}
}
}// end class
My concern is mainly regarding the while loop. Is there a way that is more efficient? Here I'm reading each line into the variable then over-writing that. I was thinking - maybe to check for when the nextInt is null ?
thanks
You can check the input using Integer.parse()
In your while loop:
String s = input.nextLine();
try{
int i = Integer.parseInt(s);
logNumber = i;
} catch(NumberFormatException ex) {
System.out.println("It is not an int");
}
If the line is not an integer or null, Exception will be thrown.
So, there are at least two ways to read a file that are relevant here.
Read the whole file into a String (or a byte[]) and then parse the whole thing at once. This fails terribly with larger files, and isn't likely faster.
Read part of the file into a buffer, parse it, then repeat until there's no more file.
The second way is more efficient for memory, as you're only taking into memory what you can handle at any one time. With they way you're doing it here, you have the single failure case of what happens with a really, really long line (what if they never hit 'enter'?), but other than that, this is safe... and chunks the work into something the machine can always fit into RAM.
Yes, you'll overwrite the value a bunch of times, but you'll only do it once per line of input, so it can't get exponentially bad, and writing things to RAM is cheap. This is likely about as efficient as it's going to get; the only reason to tune this would be if you were dealing with very, very large input sets.

Unable to read whole file, reads just one line

while(reader.hasNextLine()){
String s = reader.nextLine();
String[] tokens = s.split(" ");
while(t < tokens.length){
a = 0;
while( a < 6 ) {
if(tokens[t].equals(d[a])){
System.out.println("found keyword -> " + tokens[t]);
files = 1;
}
a++;
}
p = 0;
while( p < 2 ) {
if(tokens[t].equals(xyz[p])){
System.out.println("found token -> " + tokens[t]);
files2 = 1;
}
p++;
}
if (files2 == 0 && files == 0){
System.out.println("found identifier -> " + tokens[t]);
}
files = 0;
files2 = 0;
t++;
}
reader.close();
}
I posted something similar like this the other day, but however the while loop didn't fix it . Can some please help me through this. The problem is that it doesn't read the entire the file but only reads the one line, and that is the first line. I don't know what I am doing honestly. Thanks.
It looks like you are closing your reader (reader.close();) inside of the while loop.
As #rlinden just mentioned, be sure to reset your loop variables. Where you currently have reader.close(); make sure to set t = 0; for the next loop or take #user184994's sage advice.
Either way, you'll need to move reader.close(); outside of (below) the outermost while loop.
Is there any more code missing above this block? That could have a big effect on how the reader is functioning. Please post your new / edited code below the first block of code so I can see where any new problems are. Mark them with the tag Update:
I'll watch for edits and provide more advice if possible.
I believe that the problem is that you didn't reset t after the inside while. Try including the line
t=0;
before the inside loop.
I did not debug your code, but I assume that if the first line has a number of tokens that is equal or bigger than the second, when the second line is read t is already equal to tokens.length.
I hope it helps.
As was mentioned by others, the reader.close(); call is inside the while(reader.hasNextLine()) loop. This is causing the reader to be closed before the second line is ever read. Move it outside the outermost loop (i.e. after the } on the following line). Then address the issue of the variable t not getting set/reset.

Storing input from text file

My question is quite simple, I want to read in a text file and store the first line from the file into an integer, and every other line of the file into a multi-dimensional array. The way of which I was thinking of doing this would be of creating an if-statement and another integer and when that integer is at 0 store the line into the integer variable. Although this seems stupid and there must be a more simple way.
For example, if the contents of the text file were:
4
1 2 3 4
4 3 2 1
2 4 1 3
3 1 4 2
The first line "4", would be stored in an integer, and every other line would go into the multi-dimensional array.
public void processFile(String fileName){
int temp = 0;
int firstLine;
int[][] array;
try{
BufferedReader input = new BufferedReader(new FileReader(fileName));
String inputLine = null;
while((inputLine = input.readLine()) != null){
if(temp == 0){
firstLine = Integer.parseInt(inputLine);
}else{
// Rest goes into array;
}
temp++;
}
}catch (IOException e){
System.out.print("Error: " + e);
}
}
I'm intentionally not answering this to do it for you. Try something with:
String.split
A line that says something like array[temp-1] = new int[firstLine];
An inner for loop with another Integer.parseInt line
That should be enough to get you the rest of the way
Instead, you could store the first line of the file as an integer, and then enter a for loop where you loop over the rest of the lines of the file, storing them in arrays. This doesn't require an if, because you know that the first case happens first, and the other cases (array) happen after.
I'm going to assume that you know how to use file IO.
I'm not extremely experienced, but this is how I would think about it:
while (inputFile.hasNext())
{
//Read the number
String number = inputFile.nextLine();
if(!number.equals(" ")){
//Do what you need to do with the character here (Ex: Store into an array)
}else{
//Continue on reading the document
}
}
Good Luck.

Java split() method strips empty strings at the end? [duplicate]

This question already has answers here:
Java String split removed empty values
(5 answers)
Closed 6 years ago.
Check out the below program.
try {
for (String data : Files.readAllLines(Paths.get("D:/sample.txt"))){
String[] de = data.split(";");
System.out.println("Length = " + de.length);
}
} catch (IOException e) {
e.printStackTrace();
}
Sample.txt:
1;2;3;4
A;B;;
a;b;c;
Output:
Length = 4
Length = 2
Length = 3
Why second and third output is giving 2 and 3 instead of 4. In sample.txt file, condition for 2nd and 3rd line is should give newline(\n or enter) immediately after giving delimiter for the third field. Can anyone help me how to get length as 4 for 2nd and 3rd line without changing the condition of the sample.txt file and how to print the values of de[2] (throws ArrayIndexOutOfBoundsException)?
You can specify to apply the pattern as often as possible with:
String[] de = data.split(";", -1);
See the Javadoc for the split method taking two arguments for details.
have a look at the docs, here the important quote:
[...] the array can have any length, and trailing empty strings will be discarded.
If you don't like that, have a look at Fabian's comment. When calling String.split(String), it calls String.split(String, 0) and that discards trailing empty strings (as the docs say it), when calling String.split(String, n) with n < 0 it won't discard anything.

Categories

Resources