Java Parsefloat Exception with a string that is number followed by characters - java

When I run this line of code: Float.parseFloat("1460000 JPY") I get the error
Exception in thread "main" java.lang.NumberFormatException: For input string: "1460000 JPY"
This string is coming from an API call from a form where this is a text field with no validation. It usually works because people put in just a number, but sometimes you get this issue. How do I get it to return just the initial numbers as a float and disregard the trailing alpha characters?

You can use regex to find if that string contains only digit or not
String apistring = "1460000 JPY";
if(apistring.matches("[0-9]+")){
// do your code
}else{
// throw some error message
}
Stripping char from that will be difficult as you said its a input field and user can enter any text. You can strip it off only if you know that there is a particular pattern

Since DecimalFormat is very lenient about parsing Strings I would recommend that.
You can use it like this:
DecimalFormat df = new DecimalFormat();
try {
float parsedValue = df.parse("1460000 JPY").floatValue();
System.out.println(parsedValue);
} catch (ParseException pe) {
pe.printStackTrace();
// handle exception a bit more
}
This prints:
1460000.0
As you can see the parse method can throw a ParseException if the passed String starts with something else than a number, like:
blub 1460000 JPY
If that won't happen in your app, then you don't have to bother about it.

You can use regex to extract the numbers in input .
s = s.replaceAll("[^0-9]","");
and then parse float from it. Only downside is that it will extract all numbers (It will extract 1245 and 3 both from 1245 JPY 3).

UPDATE: to account for the bug that #Tom brought up:
Float.parseFloat("1.46 JPY".replaceAll("[^0-9.]",""));
1.46
the above is a superior solution. See below for explanation.
As #azurefrog said, stripping out non-numeric characters and then parsing what is left as a Float is the way to go.You can accomplish this using the following code:
Float.parseFloat("1460000 JPY".replaceAll("[^0-9]",""));
1460000.0
This is not very robust though, because for inputs like "1.46" the output becomes
146.0
.replaceAll("[^0-9.]","") fixes this inaccuracy by adding the decimal . character to the exclusion regex like so [^0-9.]

Related

Java console input length limit

I have an interview task where I was given a text file with file.in format, the task said that my program should be using standard data input and output (I assume console). The input file goes something like this:
249089
439506849 989399339
773359725 989399094
33290819 989399230
771114928 989399164
823133180 989399164
615096154 989399094
340750872 989399164
41881535 989399230
637599407 989399339
510268939 989399506
46219619 989399544
221332387 989399659
236968778 989399824
902942034 989399945
936095694 989400101
**end to the line 249090**
The first number is the number of objects
The second is two numbers, but for the purpose of the task I only use the second one
For the purpose of parsing the numbers I use for loop and code below:
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)))
String line = bufferedReader.readLine();
System.out.println(line);
StringTokenizer stringTokenizer = new StringTokenizer(line, " ");//
stringTokenizer.nextToken();
int height = Integer.parseInt(stringTokenizer.nextToken());
I use IntelliJ build in console and when I paste into console i get like a couple thousands results in starting from the end, so the first number is wrong, and when i run my program i get Runtime Error:
Exception in thread "main" java.lang.NumberFormatException: For input string: "84 995058150"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:658)
at java.base/java.lang.Integer.parseInt(Integer.java:776)
at pl.artur.Main.getNumberOfBuildings(Main.java:23)
at pl.artur.Main.main(Main.java:14)
Is there a way to get around it using standard input?
This has nothing to do with where the input comes from; as the stack trace shows, the exception is thrown by the Integer.parseInt method on the string "84 995058150". This string clearly does not represent a (singular) integer. If the StringTokenizer.nextToken method returns this string, then it is StringTokenizer that's the problem. As David Conrad notes in the comments, the documentation says:
StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.
The String.split method will split line into the two parts, so you can then call Integer.parseInt on the part you want:
String line = bufferedReader.readLine();
String[] parts = line.split(" ");
int height = Integer.parseInt(parts[1]);
Ok, I resolved the issue.
The solution was to set the bigger buffer size for the console in IntelliJ settings:
I think you cannot convert or parse string including empty spaces between them to Integer.
// This string cannot be parsed to Integer directly.
// Because an empty space is included between `84` and `995058150`.
String s = "84 995058150";
If you want to parse this, you should use trim() method. example:
int intValue= Integer.parseInt(s.trim());
I hope this answer will be helpful for you.

how to fix a java.lang.NumberFormatException error where the desire input is string?

i'm using Jframe as my front-end for an inventory system i have developed. I'm getting a "java.lang.NumberFormatException: For input string:"6seater"" but the variable is declared as a string so i'm a bit confused as to why this error is coming up
private String Eng_num, Chasis_num, make, model, year_of_car,capacity,description;
private Integer status,Sup_id;
public void actionPerformed(ActionEvent e)
{
Insert I = new Insert();
try
{
Chasis_num = textField_1.getText();
Eng_num = textField_9.getText();
year_of_car = textField_10.getText();
model = textField_11.getText();
make = textField_12.getText();
capacity = textField_14.getText();//error is at this line
description = textField_16.getText();
Sup_id = Integer.parseInt(""+textField_13.getText().toString());
status = Integer.parseInt(""+textField_15.getText().toString());
I.insertVehicle(Eng_num, Chasis_num, make, model, year_of_car, capacity, Sup_id, status, description);
}
I even try to put .toString and still getting the same error
capacity = textField_14.getText();
I don't think this is the cause of your exception.
java.lang.NumberFormatExceptionOnly occur when you try to parse String into any kind of Number.
So, i'm guessing, this exception was thrown somewhere you try to convert 6seater to Int or some other number format.
I'm getting a "java.lang.NumberFormatException: For input string:"6seater"" but the variable is declared as a string so i'm a bit confused as to why this error is coming up.
The error is happening because you have tried to parse the characters 6seater as an integer. It isn't an integer. An integer consists of the characters 0 through 9, possibly with a - character at the front. Any other character, and the value will be rejected ...
(The problem is nothing to do with the type that getText() returns. The problem is the value that you are giving to the parseInt method. It is not clear where the parseInt call is. A stacktrace would answer that ... but you didn't provide one.)
Also, you say:
capacity = textField_14.getText();//error is at this line
Actually, it isn't. That line cannot possibly throw a NumberFormatException. In reality, the error could be happening at one of these lines:
Sup_id = Integer.parseInt(""+textField_13.getText().toString());
status = Integer.parseInt(""+textField_15.getText().toString());
or it could be happening within the the insertVehicle method that you are calling here:
I.insertVehicle(Eng_num, Chasis_num, make, model,
year_of_car, capacity, Sup_id, status, description);
I should also point out that you have made some egregious Java style errors in your code:
Java class, method or variable names should never contain _ as a separator. Use "camel case".
A Java variable name should never start with an uppercase letter.
(If you instructor doesn't deduct "style" marks for this, he/she should. If your code reviewers don't pick this up, they are not doing their job properly. If this code was intended to be delivered to a paying customer, they would have reason to complain about the code quality ...)

Java NumberFormatException Legacy Code

I have a legacy program (java 1.4) running under Tomcat/Jboss, however, i have copy it to a new server (java 1.7) and it throws the following exception.
java.lang.NumberFormatException: For input string: "0000000000000000009011,00"
sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1250)
java.lang.Double.valueOf(Double.java:504)
java.lang.Double.<init>(Double.java:597)
Since i don't have access to the source, is there any way to fix this? i haven't try with java 1.4 for the moment
You schould look to jvm parameters on old server. Your language parameters will change comma to dot actually so you do not need any code changes.
I think its not due to java version. Replace comma(,) with "" or period(.)
For example conside a string : String str = "0000000000000000009011,00";
Now you can try -
double result = Double.valueOf(str.replace(",", "."));
or
double result = Double.valueOf(str.replace(",", ""));
Rather use NumberFormat for parsing:
NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
Number number = format.parse("0000000000000000009011,00");
double d = number.doubleValue();
This way you can select the right locale for the number representation. In the example above I used France - they use a comma for the decimal point.

Java: reading a string in a particular format

I am not posting any code I am struck with. I am trying this in Java:
Issue:
I have words like:
,xxxx-1223
yyyyy,xxdd-345
$,xxxxr-7
sdsdsdd-18
so what ever format I have I should be able to read the last one:
xxxx-1223
xxdd-345
xxxxr-7
sdsdsdd-18
what so may be the words, all I need to to get the words as shown.
Use String#lastIndexOf(int) to find where the last comma occurs, and use String#substring(int) to get the rest of the string that follows.
String input = /* whatever */;
int lastComma = input.lastIndexOf(',');
String output = input.substring(lastComma + 1);
String[] str=yourWord.split(",");
String output=str[str.length-1];
You can use this Regex: -
(\\w+-\\d+)$
Or this specific problem can simply be solved using String.split() or String.substring(int) methods

Problem with parsing String convertion to int in java

Please help me for conversion my line of codes are mention below:
String deptName = "IT";
String dept_test = request.getParameter("deptName").trim();
System.out.println("Dept name vlue is"+dept_test);
// problem here for casting...
int dept_id = Integer.parseInt(dept_test);
I don't see any casting problems. If your text doesn't contain a parseable number you will get a NumberFormatException which you may need to catch with a try/catch block. What exactly is the problem you are having?
From looking at your code the most you get will be an error parsing the input (including if it is none. What may be an issue is that the variable deptName is never used. Did you mean to make the second line
String dept_test = request.getParameter(deptName).trim();
(notice no quotes) instead?

Categories

Resources