In android I am getting the String value from BufferedReader and it is null after reading from file.
intstring = br.readLine();
System.out.println(intstring);
if(intstring != null)
{
System.out.println("Inside if condition");
int istring = Integer.parseInt(intstring);
}
My output is
null
Inside if condition
NumberFormatException
Help me please
Your NumberFormatException is happening because your input isn't a number. Maybe it's a blank line, or maybe it has some non-numeric characters. In fact, your output suggests that it's actually the word "null".
You've got some options.
You could check that the string contains digits and no other characters before you parse it, for example by using a regular expression and a condition like if (intString.matches("\\d+")).
You could catch the NumberFormatException, and do something particular when it happens.
You could check whether your string is blank, if you knew that there weren't going to be any non-numeric characters in the input. For this option, you might write if (!intString.equals(""))).
Related
I am using a method with a BufferedReader with FileReader to read a file. The file consists of several lines of items separated by multiple white spaces. I am looping through the each line of the file using a while loop with the condition that the line I just read isn't null or blank.
I read the the first line and then enter the loop and then I get a NullPointerException that my line is null, but it shouldn't be because I just read it.
public ReadFile(String filename) {
try {
BufferedReader br = new BufferedReader(new FileReader(filename));
String ln;
ln = br.readLine();
// loops as long as the last line read is not null or blank
while (ln != null || ln.length() != 0) {
//do stuff with ln
ln = br.readLine();
}
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
I was expecting to loop through reading the file line by line until either the line was null or blank (in case the last line is ""). This however does not happen and the line is null when the while loop is run. I tried this same exact implementation but in a different file in the main function and it worked perfect so I am very confused with what's wrong.
Well, basically it's because of your conditional check.
The javadoc says that the method readLine() returns:
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached.
So at the end of the stream you'll get a null. Now, because of the OR (||) operator you have in the while loop, your conditional statements will be checked until you find a true statement.
This is because of 'short-circuits-logical-operators' in Java.
So you'll check the condition:
ln!=null => false
and then because the Or is searching for a true condition, you'll check
ln.length() => and get a NullPointerException
If you want to avoid this, you can use the && (and) operator with the same conditions.
This way, if the ln is null, you'll check the first condition
ln!=null => false
and then because the And operator requires every condition to be true to be verified, you'll interrupt the while loop.
while (ln != null && ln.length() != 0){
//do stuff with ln
ln = br.readLine();
}ln = null;
Keep in mind however, that if you have a line that is empty "" it's length will be 0, so the while loop will stop.
Well, I think that you can change your code to:
while (ln!=null) {
//we check if the line is not empty
if(ln.length() !=0) {
//do your operations
}
//read the next line
ln = br.readLine();
}
The process is to first check if the line is null. If it's not null, then check if it has content. If it does have content, perform your operation on the non-empty, non-null line. In all cases, read the next line.
I'm printing a single string from a server which contains multiple '\n' in it and would like to clear the screen before each new message. However, the following code causes the screen to be cleared after each line in the single string.
while (true) {
String s = server.readLine();
if (s == null) {
throw new NullPointerException();
}
ConsoleCleaner.clean();
System.out.println(s.toString());
}
Again, s is one single string with multiple '\n' inside which leads to one line being printed and the screen cleared each time.
I'm assuming that server is a BufferedReader here, since you haven't specified otherwise. And for the purpose of BufferedReader.readLine(), there's no such thing as "a single string with multiple \n". When the method encounters the first \n, that's the output of readLine().
You could avoid this issue by keeping track of the non-whitespace length of the last message printed, and only clearing the screen when it's non-zero.
Could you adapt this example to reach your requirement?
Read all lines with BufferedReader
Perhaps like this:
String s;
while ((line = server.readLine()) != null) {
s += line + (System.getProperty("line.separator"));
}
ConsoleCleaner.clean();
System.out.println(s.toString());
Not tried this...
I was working on some code using try-catch and I needed empty substrings to throw an exception when doing Double.parseDouble() (in this case, I presume it would be a NullPointerException).
My question is why this code doesn't throw an exception if I enter something like , , , (space-comma-space-comma-space-comma) or similar (which should split the string into three whitespaces, if I understand correctly):
Scanner input = new Scanner(System.in);
String[] inputParts = null;
String inputLine = input.nextLine();
// the matches() here prevents this from happening, but I still don't understand
// why an exception isn't thrown
if ((inputLine.contains(",") || inputLine.contains(" ")) && !inputLine.matches("\\s+")) {
inputParts = inputLine.split("\\s*(,*\\s+)|(,+)");
}
for (int i = 0; i < inputParts.length; ++i) {
// this prints nothing -- not even a new line. Same behavior even if I don't parseDouble
// and just print the string directly
System.out.println(Double.parseDouble(inputParts[i]));
}
If I try to parseDouble from an empty string "" or " " without taking user input like this it does throw an exception.
I'm quite confused as to why this is happening, considering the code I was working on does work except when I enter something like the above (although I fixed it by checking to see if each substring was only whitespace and throwing the appropriate exception manually).
Thanks.
This is the code for reading input from a file which contains student details in the form roll,name,age,street,city,zipcode.
Few values among these can be null even.
For the following code, I am getting java.lang.ArrayIndexOutOfBoundsException: 1
Code is as follows-
BufferedReader br=new BufferedReader(new FileReader(fileName));
while((line=br.readLine())!=null){
split_array=line.split("\\,");
String roll1=split_array[0];
String name=split_array[1];// This is the line which causes Exception
String age1=split_array[2];
String street=split_array[3];
String city=split_array[4];
String zip=split_array[5];
}
If you have empty lines in the middle of the file, you should
if (line.equals(""))
continue;
or
if (split_array.length <= 1)
continue;
after calling split()
you should use a delimiter to separate each column.
Check the length before using the Indexes since you said some data could be missing so sometimes the index will be out of bound.
Its always good practice to assume that sometimes the user wouldn't provide the data in the required format.
I have a problem over my application. I want the app to detect that if the user does not input any value for the string (in other words, just press enter after being asked to input something), the app then asks whether he/she wishes to quit the program or not.
Am I doing it right?
words = s.nextLine();
if (words.equals(null)) {
No, you're not doing it right.
nextLine() will return an empty string if the user just hits return. As far as I can tell it will never return null. If the end of the input has been reached, it will throw NoSuchElementException (unlike BufferedReader.readLine() which will return null in that case). So you want:
if (words.equals(""))
or
if (words.length() == 0)
or
if (words.isEmpty())
... and use hasNextLine() if you want to detect the end of input first.
No, you're not.
If the user simply presses enter, you'll get an empty string, not null. This can be checked as
if(words.equals(""))
If there are whitespaces, this would fail. In that case
if(words.trim().equals(""))
should work.
null is not correct, because what you get is an empty String:
use:
words.isEmpty()
or
words.equals("")
or
words.length()==0
This should work:
if (words == null || words.length() == 0) {
the returned string isnt null, its just an empty string.
words.equals("");
should be correct