I'm parsing a doc and I get the following error:
Exception in thread "main" java.lang.NumberFormatException: For input string: "null"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1222)
at java.lang.Float.valueOf(Float.java:388)
at CentroidGenerator$Centroid.averageLat(CentroidGenerator.java:403)
at CentroidGenerator.getCentroids(CentroidGenerator.java:30)
at CentroidGenerator.main(CentroidGenerator.java:139)
This is the part of code throwing the exception:
if (latitude!=null) {
//if (!latitude.equals("null")) {
String[] latValues = latitude.split(" ");
float sum = 0;
for (int i = 0; i < latValues.length; i++) {
sum = sum + Float.valueOf(latValues[i].trim()).floatValue();
}
latitude = Float.toString(sum / (float) latValues.length);
//}
}
As you can see I've tried to check for "null" strings but even uncommenting the second if statement I get the same error.
thanks
Maybe one of the values is "null" (for example, the string : "123.4 null 5 null") not the first one, so I think a proper solution will be:
String[] latValues = latitude.split(" ");
float sum = 0;
for (int i = 0; i < latValues.length; i++) {
if (!latValues[i].equals("null"))
sum = sum + Float.valueOf(latValues[i].trim()).floatValue();
}
latitude = Float.toString(sum / (float) latValues.length);
or instead, add try-cath inside the for loop and ignore values that are not numbers.
EDIT
As pointed in comments (Sualeh), it is better to use try / catch because today it's "null" tomorrow it's something else (i.e. double spaces...).
try {
sum = sum + Float.valueOf(latValues[i].trim()).floatValue();
}
catch (NumberFormatException e)
{
// log e if you want...
}
To avoid issues with strings like "1 2", with multiple spaces, which give null values, it is best to add a try-catch inside the loop, like this:
if (latitude != null) {
String[] latValues = latitude.split(" ");
float sum = 0;
for (int i = 0; i < latValues.length; i++) {
try {
sum = sum + Float.valueOf(latValues[i].trim()).floatValue();
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
latitude = Float.toString(sum / (float) latValues.length);
}
It is pretty clear that the problem is that you have an input line that has the characters "null" instead of one of the numbers. But I don't think that ignoring the nulls is necessarily the right thing to do.
First, you need to figure out what those nulls really mean:
Do they denote missing data-points (latitude values)?
Are they a symptom of a bug in the code that captured the original latitude data?
are they a symptom of a bug in the code that read the data from an input file / database?
Then maybe you need to track down the bug / bugs or adjust your processing to deal with the missing data.
Based on your error, it is very possible your latValues[i].trim() displays the value "null". I'm able to replicate your problem here:-
Float.valueOf("null");
Here's the stacktrace:-
java.lang.NumberFormatException: For input string: "null"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1301)
at java.lang.Float.valueOf(Float.java:375)
In another word, the value you have is not null, but it contains the word "null".
If you do Float.valueOf(null);, that actually gives you a NullPointerException, which is not what you have here.
The call of the trim function is useless. If you really want to screen your input data to avoid the NumberFormatException you find the code in the JavaDocs for Doubles
The parseInt() and parseDouble() will error with NFE if passed with a null, space or blank string value. Once you have handled the null condition it will still fail with an empty string. Try adding a zero before the empty string like below. It maintains the integrity of calc as well:
Integer.parseInt(" ".trim())
to
Integer.parseInt( "0" + " ".trim())
Related
So I'm trying to solve the Longest Substring Without Repeating Character problem in a webpage and when I'm trying to upload it it will show me this bug:
class Solution {
public int lengthOfLongestSubstring(String s) {
HashSet<Character> hash = new HashSet<>();
int count = 0, finalCount = 1;
char prevChar = s.charAt(0);
hash.add(prevChar);
for (int i = 1; i < s.length(); i++)
{
char character = s.charAt(i);
if (!hash.contains(character)){
hash.add(character);
count++;
if (count > finalCount) finalCount = count;
}
else{
hash.clear();
hash.add(character);
count = 1;
}
prevChar = character;
}
return finalCount;
} }
Is there anything wrong with it?
If not, do you think my algorithm was efficient? I can't compare its performance since the webpage won't let me upload it.
You call s.charAt(0) in line 5. I imagine they pass in the empty string as a test case and you are getting an out of bounds exception. Prior to line 5 add a check to see if the string length is 0 and if it is return 0.
According to the error description it's doing a dummy-spit at line 5 of the Solution class.
Based on the picture that's:
char prevChar = s.charAt(0);
The error is ArrayIndexOutOfBounds which generally indicates you tried to get more out of something than was actually there (e.g. running over the end of an array).
Here I'd suggest maybe putting in some System.out.println lines at line 3 to sanity check the method parameter, e.g.:
(a) if the input String s is null
or
(b) if the input String s is empty (e.g. "")
charAt(0) will get the first character, but if there are zero characters then trying to get the 1th character is an error, no?
NB: something like this:
System.out.println("Input was :" + s + ":");
Will show both of those conditions, as either:
Input was ::
for an empty String
Input was :null:
for a null String
I'm working on an app in which the user has the option to input a set of coordinates in two EditText views for Latitude and Longitude. The inputted coordinate/location will then be displayed on a map, which works great. However if the user inputs an invalid value the app crashes, and I need to prevent that.
The Latitudes/Longitudes value has to be for example 35.27, and the thing that makes the app crash is when there's more then one dot "." e.g. 33.23.43. How can i check if the inputted value only has ONE dot?
I don't really have a lot of experience in this area, and I'm still new to android, so any help will be much appreciated.
I was going to suggest that you checked the length of the string that you get, but because 1.5 and 153.163 are both valid that doesn't work. I advise you to use a `try/catch statement. For example
try{
//do what ever you do with the numbers here
catch(Exception e){
//the user has inputted an invalid number deal with it here
}
Check out
Android EditText : setFilters Example : Numeric Text field Patterns and Length Restriction.
It may be what you want.
bool badInput = countChar(s, '.') > 1;
where countChar is
int countChar(string s, char c)
{
int counter = 0;
for( int i=0; i<s.length(); i++ ) {
if( s.charAt(i) == c ) {
counter++;
}
}
return counter;
}
Simply use a regexp to check the validity of the input.
Pattern p = Pattern.compile("^(-)?\d*(\.\d*)?$");
Matcher m = p.matcher(inputString);
if (m.find()) {
////Found
}
else {
//Not found
}
Now Implement a focus listener on the field to run this validity test.
OR : you can do this from xml also.
In XML add attribute to editText :
android:inputType="number|numberSigned|numberDecimal"
for signed floating point number.
Thanks.
I am working on a class assignment this morning and I want to try and solve a problem I have noticed in all of my team mates programs so far; the fact that spaces in an int/float/double cause Java to freak out.
To solve this issue I had a very crazy idea but it does work under certain circumstances. However the problem is that is does not always work and I cannot figure out why. Here is my "main" method:
import java.util.Scanner; //needed for scanner class
public class Test2
{
public static void main(String[] args)
{
BugChecking bc = new BugChecking();
String i;
double i2 = 0;
Scanner in = new Scanner(System.in);
System.out.println("Please enter a positive integer");
while (i2 <= 0.0)
{
i = in.nextLine();
i = bc.deleteSpaces(i);
//cast back to float
i2 = Double.parseDouble(i);
if (i2 <= 0.0)
{
System.out.println("Please enter a number greater than 0.");
}
}
in.close();
System.out.println(i2);
}
}
So here is the class, note that I am working with floats but I made it so that it can be used for any type so long as it can be cast to a string:
public class BugChecking
{
BugChecking()
{
}
public String deleteSpaces(String s)
{
//convert string into a char array
char[] cArray = s.toCharArray();
//now use for loop to find and remove spaces
for (i3 = 0; i3 < cArray.length; i3++)
{
if ((Character.isWhitespace(cArray[i3])) && (i3 != cArray.length)) //If current element contains a space remove it via overwrite
{
for (i4 = i3; i4 < cArray.length-1;i4++)
{
//move array elements over by one element
storage1 = cArray[i4+1];
cArray[i4] = storage1;
}
}
}
s = new String(cArray);
return s;
}
int i3; //for iteration
int i4; //for iteration
char storage1; //for storage
}
Now, the goal is to remove spaces from the array in order to fix the problem stated at the beginning of the post and from what I can tell this code should achieve that and it does, but only when the first character of an input is the space.
For example, if I input " 2.0332" the output is "2.0332".
However if I input "2.03 445 " the output is "2.03" and the rest gets lost somewhere.
This second example is what I am trying to figure out how to fix.
EDIT:
David's suggestion below was able to fix the problem. Bypassed sending an int. Send it directly as a string then convert (I always heard this described as casting) to desired variable type. Corrected code put in place above in the Main method.
A little side note, if you plan on using this even though replace is much easier, be sure to add an && check to the if statement in deleteSpaces to make sure that the if statement only executes if you are not on the final array element of cArray. If you pass the last element value via i3 to the next for loop which sets i4 to the value of i3 it will trigger an OutOfBounds error I think since it will only check up to the last element - 1.
If you'd like to get rid of all white spaces inbetween a String use replaceAll(String regex,String replacement) or replace(char oldChar, char newChar):
String sBefore = "2.03 445 ";
String sAfter = sBefore.replaceAll("\\s+", "");//replace white space and tabs
//String sAfter = sBefore.replace(' ', '');//replace white space only
double i = 0;
try {
i = Double.parseDouble(sAfter);//parse to integer
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
}
System.out.println(i);//2.03445
UPDATE:
Looking at your code snippet the problem might be that you read it directly as a float/int/double (thus entering a whitespace stops the nextFloat()) rather read the input as a String using nextLine(), delete the white spaces then attempt to convert it to the appropriate format.
This seems to work fine for me:
public static void main(String[] args) {
//bugChecking bc = new bugChecking();
float i = 0.0f;
String tmp = "";
Scanner in = new Scanner(System.in);
System.out.println("Please enter a positive integer");
while (true) {
tmp = in.nextLine();//read line
tmp = tmp.replaceAll("\\s+", "");//get rid of spaces
if (tmp.isEmpty()) {//wrong input
System.err.println("Please enter a number greater than 0.");
} else {//correct input
try{//attempt to convert sring to float
i = new Float(tmp);
}catch(NumberFormatException nfe) {
System.err.println(nfe.getMessage());
}
System.out.println(i);
break;//got correct input halt loop
}
}
in.close();
}
EDIT:
as a side note please start all class names with a capital letter i.e bugChecking class should be BugChecking the same applies for test2 class it should be Test2
String objects have methods on them that allow you to do this kind of thing. The one you want in particular is String.replace. This pretty much does what you're trying to do for you.
String input = " 2.03 445 ";
input = input.replace(" ", ""); // "2.03445"
You could also use regular expressions to replace more than just spaces. For example, to get rid of everything that isn't a digit or a period:
String input = "123,232 . 03 445 ";
input = input.replaceAll("[^\\d.]", ""); // "123232.03445"
This will replace any non-digit, non-period character so that you're left with only those characters in the input. See the javadocs for Pattern to learn a bit about regular expressions, or search for one of the many tutorials available online.
Edit: One other remark, String.trim will remove all whitespace from the beginning and end of your string to turn " 2.0332" into "2.0332":
String input = " 2.0332 ";
input = input.trim(); // "2.0332"
Edit 2: With your update, I see the problem now. Scanner.nextFloat is what's breaking on the space. If you change your code to use Scanner.nextLine like so:
while (i <= 0) {
String input = in.nextLine();
input = input.replaceAll("[^\\d.]", "");
float i = Float.parseFloat(input);
if (i <= 0.0f) {
System.out.println("Please enter a number greater than 0.");
}
System.out.println(i);
}
That code will properly accept you entering things like "123,232 . 03 445". Use any of the solutions in place of my replaceAll and it will work.
Scanner.nextFloat will split your input automatically based on whitespace. Scanner can take a delimiter when you construct it (for example, new Scanner(System.in, ",./ ") will delimit on ,, ., /, and )" The default constructor, new Scanner(System.in), automatically delimits based on whitespace.
I guess you're using the first argument from you main method. If you main method looks somehow like this:
public static void main(String[] args){
System.out.println(deleteSpaces(args[0]);
}
Your problem is, that spaces separate the arguments that get handed to your main method. So running you class like this:
java MyNumberConverter 22.2 33
The first argument arg[0] is "22.2" and the second arg[1] "33"
But like other have suggested, String.replace is a better way of doing this anyway.
My program reads lines from a plain text file w/ lines formatted: <integer>;<integer>%n, where ; is the delimiter. It compares the two parsed integers against 2 other known values and increments tallyArray[i] if they match.
I currently use:
try {
scan = new Scanner(new BufferedReader(new FileReader("LogFileToBeRead.txt")));
for (int i = 0; i < tallyArraySize; i++) {
explodedLogLine = scan.nextLine().split(";");
if (IntReferenceVal1 == Integer.parseInt(explodedLogLine[0]) && IntReferenceVal2 == Integer.parseInt(explodedLogLine[1])) {
tallyArray[i]++;
}
}
} finally {
if (scan != null) { scan.close(); }
}
I was wondering if there were any serious faults with this method. It does not need to be production-quality.
Also, is there a standard way of parsing a string like this?
EDIT: We can assume the text file is perfectly formatted. But I see the importance for accounting for possible exceptions.
You are not handling NumberFormatExceptions thrown by the Integer.parseInt() method calls. If there's one bad line, execution exits your for loop.
You aren't vetting the integrity of the file you are reading from. If there isn't a ; character or if the Strings aren't actually numbers, execution simply exits the code block you posted.
If you can assume the file is perfectly formatted, and you're set on using a Scanner, you can add ; as a delimiter to the Scanner:
scan = new Scanner(new BufferedReader(new FileReader("LogFileToBeRead.txt")));
scan.useDelimiter(Pattern.compile("(;|\\s)"));
for (int i = 0; i < tallyArraySize; i++) {
int ref1 = scan.nextInt();
int ref2 = scan.nextInt();
if (IntReferenceVal1 == ref1 &&
IntReferenceVal2 == ref2) {
tallyArray[i]++;
}
}
And simply call Scanner.nextInt() twice for each line.
According to me There are three flaws in the program.
Delimiter ; what if there is delimiter is removed by accident or added by accident
There should be check on explodedLogLine that it is of length 2 and it is not null otherwise it will result in unexpected runtime error
You should catch NumberFormatException format exception since you can never be sure that Input is always a number
A simple illustration below gives you idea how things will go wrong.
String str = "3;;3";
System.out.println(Arrays.toString(str.split(";")));
This code will print [3, , 3] in such case your program will produce NumberFormatException as "" string can not be parsed to Integer.
Hy!
I want to parse a String to a Integer.
The String is like the format for series: SXXEXXX
The Code should increase the episode.
Like: S01E01 --> S01E02
Also: S01E100 --> S01E101
Code:
String s = episodes.get(episodes.size()-1);
Log.e("DBManager",s);
if (s.split("E").length <= 2) {
int i = Integer.getInteger(s.split("E")[1].split(" ")[0]); //NullPointerEx
return s.split("E")[0]+"E"+String.valueOf(i++);
}
Log:
10-26 15:56:34.635: E/DBManager(932): S00E01
Integer.getInteger() is not the correct method to use.
You should be using Integer.valueOf()
Integer.getInteger(String s) will return the integer system property with the key s.
The null pointer occurs because this method can't find the property with the key you supply and returns null. Java then tries to unbox this to an int and null pointers.
The null pointer exception is occuring precisely because you leave the leading 0 in the string. If you really need to leave it in there though, the following code works for me:
int i = Integer.parseInt(s.split("E")[1].split(" ")[0]);
If I understand correctly, you want to split the episode name into the parts, then get the episode number and increment it by one to get the next episode number. Don't call this split method so many times, call it once.
String episodeName = episodes.get(episodes.size()-1);
Log.e("DBManager", episodeName);
string[] splittedName = episodeName.split("E");
string returnName = "";
if (splittedName.length == 2) {
if (splittedName[1].split(" ").length > 1) {
// do something if there's a episode name too
} else {
// gets the episode number
int i = Integer.valueOf(splittedName[1]);
// returns next episode full name
if (i < 9) {
returnName = splittedName[0] + "E0" + String.valueOf(i + 1);
} else {
returnName = splittedName[0] + "E" + String.valueOf(i + 1);
}
}
}
return returnName;