Getting NumberFormat while trying to parse a string - java

I'm trying to parse a string to an integer. The string is a number when I do sys out but when I try to parse it then it adds a double quote at the beginning. I'm not doing anything additional.
Following is a snippet of my code:
System.out.println("Result 2 is: "+results[2]);
String temp = results[2].replace("\"", "");
System.out.println("String Temp is: "+temp);
int height = Integer.parseInt(results[1].replace("\"", ""));
int width = Integer.parseInt(results[2].replace("\"", ""));
In the logs:
String Temp is: 2550
wt.system.err wcadmin - java.lang.NumberFormatException: For input string: "2550
This exception is only for result[2]. Something to do with character set?

Option 1: Parse temp. Change
int width = Integer.parseInt(results[2].replace("\"", ""));
to
int width = Integer.parseInt(temp);
Option 2: Use a regular expression to remove everything not a digit instead of trying to handle corner cases by hand.
int width = Integer.parseInt(results[2].replaceAll("\\D+", ""));

Related

how to get value from web and convert it into integer

I want to get value from web
For eg : Total AMount : 25000
and want to convert this value into integer to proceed comparision step but after printing totat_Amt it displayed as
"java.lang.NumberFormatException: For input string: "25,000""
Here is my code :
WebElement gt = driver.findElement(By.id("totAmt"));
String total_Amt=gt.toString();
System.out.println("Total Amt:"+total_Amt);
//int total_amt_val =Integer.parseInt(total_Amt);
System.out.println(total_amt_val);
Try to replace all non-numeric symbols:
WebElement gt = driver.findElement(By.id("totAmt"));
String total_Amt = gt.toString(); // "25,000"
// replace 'bad' symbols
String onlyNumbers = total_Amt.replaceAll("[^\\d]", ""); // "25000"
System.out.println("Total Amt: " + total_Amt);
int total_amt_val = Integer.parseInt(onlyNumbers); // 25000
System.out.println(total_amt_val);
\\d means all numbers, [^\\d] means all non-numbers, and if you want to keep some another symbols, just add them into [] — e.g. use [\\d.] if you want to keep dots too.
You can use NumberFormat
NumberFormat.getNumberInstance(Locale.US).parse("25,000").intValue() will return 25000
You can try this:
WebElement gt = driver.findElement(By.id("totAmt"));
String total_Amt = gt.toString(); // 25,000
total_Amt = total_Amt.replaceAll(",", ""); // removes all ',' -> 25000
int total_amt_val = Integer.parseInt(total_Amt); // 25000 as int already
System.out.println(total_amt_val); // 25000
You can replace all the comma first using replaceAll method and then directly parse it as below. additionally, you need to use getText() method should be used to retrieve the element text.
WebElement gt = driver.findElement(By.id("totAmt"));
//To be changed as gt.getText().
String total_Amt=gt.getText();
System.out.println("Total Amt:"+total_Amt);
//Replace comma as empty and then you can normal parse the string to int
int total_amt_val =Integer.parseInt(total_Amt.replaceAll(",",""));
System.out.println(total_amt_val)
In case , If you are getting the total_Amt value as Total AMount : 25000, then extract the amount value using substring method and then replace all the , as empty using replaceAll method
int total_amt_val =Integer.parseInt(total_Amt.substring(total_Amt.indexOf(":")+2).replaceAll(",",""));
If you are dealing with price, use this:
public static void main(String[] args) throws Exception {
WebElement gt = driver.findElement(By.id("totAmt"));
String total_Amt = gt.getText(); // total_Amt=25,000.00
BigDecimal bd_amt = parse(total_Amt , Locale.US); // Use this if the value is price
int int_amount = parse(total_Amt , Locale.US).intValueExact(); // Use this if you want integer
System.out.println("Price : " + bd_amt);
System.out.println("Amount : " + int_amount);
}
private static BigDecimal parse(final String amount, final Locale locale) throws ParseException {
final NumberFormat format = NumberFormat.getNumberInstance(locale);
if (format instanceof DecimalFormat) {
((DecimalFormat) format).setParseBigDecimal(true);
}
return (BigDecimal) format.parse(amount.replaceAll("[^\\d.,]", ""));
}
Sample Output:
Price : 25000.00
Amount : 25000

How to convert string with $ sing in it to int

I have a string "$1,076.00" and I want to convert them in to int,
I capture some value $1,076.00 and saved in string called originalAmount,
and tried int edited = Integer.parseInt(originalAmount); and it gave me error java.lang.NumberFormatException: For input string: "$1,076.00"
can anyone help?
You need to remove the undesired part ($ sign) and then parse the string to double carefully since the decimal part is a locale dependent
String pay = "$1,076.00";
NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
Number number = format.parse(pay.replace("$", ""));
double result = number.doubleValue();
System.out.println(result);
string sourceString = "$1,076.00";
sourceString.substring(1, sourceString.length() - 1)
int foo = Integer.parseInt(sourceString);
Try this:
String amount = "$1,076,.00";
String formatted = amount.replace("$", ""); // remove "$" sign
formatted = formatted.replace(",", ""); // remove "," signs from number
double amountDouble = Double.parseDouble(formatted); // convert to double
int amountInt = (int)amountDouble; // convert double value to int
System.out.println(amountInt); // prints out 1076
String originalAmount="$1076.00";
String amount = originalAmount.replace($,"");
int edited = Integer.parseInt(amount);
Thanks everyone yr answers help me a lot
I have come up with
originalAmount = originalAmount.substring(1);
if (originalAmount.contains("$")) {
originalAmount = originalAmount.replace("$", "");
}
newOriginalAmt = Double.parseDouble(originalAmount);
System.out.println(newOriginalAmt);
pls let me know yr thoughts

Convert $16500.00 String to 16500 Integer

Im having an issue trying to convert $16500.00 String to 16500 Integer.
This is what i have at the moment but its failing with:
FATAL EXCEPTION: main
java.lang.NumberFormatException: Invalid int: "[]"
The code i have is:
String depTest = mDepositAmount.getText().toString();
String deptest2 = Arrays.toString(depTest.replace("R", "").replace(",", "").split("."));
int dep = Integer.parseInt(deptest2);
Please could you help me with getting the end result to 16500. I know how to convert it to int by using Integer.parseInt its just im struggling to get the end result to be 16500 in String
Does your original string always starts with character '$' and followed by number format?
If so try this one:
String org = "$16500.00";
String numbersOnly = org.substring(1); // "16500.00"
int yourInteger = (int)(Float.parseFloat(numbersOnly));
// if you need String, convert it to String again
String integerString = Integer.toString(yourInteger);
You could use a DecimalFormat
import java.text.*;
NumberFormat nf = new DecimalFormat("$0.00");
int value = (int) nf.parse("$16500.00");
You can try with this
String getValue = "$16500.00";
String removeFirstCharecter = getValue.substring(1); // "16500.00"
String [] getString = removeFirstCharecter.split("\\.");
String firstIntValue = (getString[0]); //16500
String sirstIntValue = (getString[1]); //00
Now you can convert firstIntValue String to Integer .
String getRequiredValue = Integer.toString(firstIntValue); //16500
It may be happen because of $ sign so, Just take one another Text view only for Price 16500 and other for $ sign. then convert the Integer.parseInt(textview.getText().toString);

What does this NumberFormatException mean?

java.lang.NumberFormatException: For input string: ":"
What does this mean?
I get the above error if I run the code (below).I am a beginner here.
and..
stacktrace:[Ljava.lang.StackTraceElement;#e596c9
the code:
try
{
Class.forName("java.sql.DriverManager");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/bvdb","root","enter")
Statement stm=con.createStatement();
String m="-",t="-",w="-",th="--",f="-",st="--",s="-",runson;
if(jCheckBox1.isSelected()==true){
m="m";}
if(jCheckBox2.isSelected()==true){
t="t";}
if(jCheckBox3.isSelected()==true){
w="w";}
if(jCheckBox4.isSelected()==true){
th="th";}
if(jCheckBox5.isSelected()==true){
f="f";}
if(jCheckBox6.isSelected()==true){
st="st";}
if(jCheckBox7.isSelected()==true){
s="s";}
runson= m + t + w + th + f + st + s ;
int h1=Integer.valueOf(jTextField10.getText().substring(0,2)
int mins1=Integer.valueOf(jTextField10.getText().substring(3,5));
int h2=Integer.valueOf(jTextField12.getText().substring(0,2));
int mins2=Integer.valueOf(jTextField12.getText().substring(2,3));
Boolean x=jTextField10.getText().substring(2,3).equals(":");
Boolean y=jTextField12.getText().substring(2,3).equals(":");
String time1=jTextField10.getText().substring(0,2)+jTextField10.getText().substring (2,3)+jTextField10.getText().substring(3,5);
String time2=jTextField12.getText().substring(0,2)+jTextField12.getText().substring(2,3)+jTextField12.getText().substring(3,5);
String tfac1=jTextField13.getText();
String tfac2=jTextField14.getText();
String tfac3=jTextField15.getText();
String tfsl=jTextField16.getText();
if(Integer.valueOf(jTextField3.getText())==0){
tfac1="0";
if(Integer.valueOf(jTextField4.getText())==0){
tfac2="0";}
if(Integer.valueOf(jTextField5.getText())==0){
tfac3="0";}
if(Integer.valueOf(jTextField6.getText())==0){
tfsl="0";}
if(y==true&&x==true&&jTextField1.getText().trim().length()<=6&&jTextField2.getText().trim().length()<=30&&h1<=24&&h2<=24&&mins1<=59&&mins2<=59){
String q="INSERT INTO TRAININFO VALUE ("+jTextField1.getText()+",'"+jTextField2.getText()+"','"+jTextField9.getText()+"','"+time1+"','"+jTextField11.getText()+"','"+time2+"','"+runson+"',"+tfac1+","+tfac2+ ","+tfac3+","+tfsl+","+jTextField3.getText()+","+jTextField4.getText()+","+jTextField5.getText()+","+jTextField6.getText()+");";
stm.executeUpdate(q);
JOptionPane.showMessageDialog("ADDED");
}
}
catch (Exception e){
e.printStackTrace();
}
that means you can not convert the String ":" to Number like integer or double
see below link
http://docs.oracle.com/javase/7/docs/api/java/lang/NumberFormatException.html
According to java docs
Thrown to indicate that the application has attempted to convert a
string to one of the
numeric types, but that the string does not have the appropriate format.
It means you want to convert ":" to a number which is not allowed. Hence you are getting the exception. Better show your code
The best way you get responses faster & answered your question is posting your code.
You cannot convert String to number.
As others have said Java can't convert "15:" into a number because ":" is not a digit. And the most probable cause for this is a line like this one:
int h1 = Integer.valueOf(jTextField10.getText().substring(0,2));
where you are splitting a time string at the wrong index which is why you have ":" in it.
UPDATE
Better way of splitting a time string like "12:35:09" is by using String.split():
String timeString = "12:35:09";
String[] parts = timeString.split(":");
boolean validTimeString = parts.length == 3;
The code above will result in the following values:
timeString = "12:35:09"
parts[0] = "12"
parts[1] = "35"
parts[2] = "09"
validTimeString = true
String.split(DELIMITER) will split the string into N + 1 strings where N is the number of occurences of the DELIMITER in target string.

Building a pattern to extract data out of a string

I have strings of the form:
"abc" 1 2 1 13
"efgh" 2 5
Basically, a string in quotes followed by numbers separated by whitespace characters.
I need to extract the string and the numbers out of the line.
So for eg., for the first line, I'd want
abc to be stored in a String variable (i.e. without the quotations) and
an array of int to store [1,2,1,13].
I tried to create a pattern that'd do this, but I'm a little confused.
Pattern P = Pattern.compile("\A\".+\"(\s\d+)+");
Not sure how to proceed now. I realized that with this pattern I'd kinda be extracting the whole line out? Perhaps multiple patterns would help?
Pattern P1 = Pattern.compile("\A\".+\"");
Pattern P2 = Pattern.compile("(\s\d+)+");
Again, not very sure how to get the string and ints out of the line though. Any help is appreciated!
I would rather just split the string on space, rather than building complex regex, and use it with Pattern and Matcher class.
Something like this: -
String str = "\"abc\" 1 2 1 13 ";
String[] arrr = str.split("\\s");
System.out.println(Arrays.toString(arrr));
OUTPUT: -
["abc", 1, 2, 1, 13]
Shows your intent much clearer, that what you want to do.
Then, you can get the string and integer parts from your string array. You would need to do a Integer.parseInt() on integer elements.
If your string may contain spaces in it, then in that case, you would need a Regex. Better one would be the one in #m.buettner's answer
Use capturing groups to get both parts in one go, then split the numbers at spaces.
Pattern pattern = Pattern.compile("\"([^\"]*)\"\\s*([\\d\\s]*)");
Matcher m = pattern .matcher(input);
while (m.find()) {
String str = m.group(1);
String[] numbers = m.group(2).split("\\s");
// process both of them
}
Each set of parentheses in the regex will later correspond to one group (counting opening parentheses from left to right, starting at 1).
Please try this it will separate both String and int also
String s = "\"abc\" 1 2 1 13 ";
s = s.replace("\"", "");
String sarray[] = s.split(" ");
int i[] = new int[10];
String si[] = new String[10];
int siflag = 0;
int iflag = 0;
for (String st : sarray) {
try {
int ii = Integer.parseInt(st)
i[iflag++] = ii;
} catch (NumberFormatException e) {
si[siflag++] = st;
}
}
StringTokenizer st = new StringTokenizer(str,"\" ");
String token = null;
String strComponent = null;
int num[] = new int[10]; // can change length dynamically by using ArrayList
int i = 0;
int numTemp = -1;
while(st.hasMoreTokens()){
token = st.nextToken();
try{
numTemp = Integer.parseInt(token);
num[i++] = numTemp ;
}catch(NumberFormatException nfe){
strComponent = token.toString();
}

Categories

Resources