I have to convert String into float I am doing it like this :
float[] iLongs = new float[mLongs.length];
for(int i = 0; i < iLongs.length ; i++){
iLongs[i] = Float.valueOf(mLongs[i]).floatValue();
}
But it throws numberformat exception
But if I use the same function outside any loop it works.
What to do ?
The code looks fine, which leads me to suspect that it's a data issue. You need to verify that every index for mLongs contains a String that is actually valid as a float, how you do that is up to you.
Alternative code :
class StringToFloat {
public static void main (String[] args) {
// String s = "hello"; // do this if you want an exception
String s = "100.00";
try {
float f = Float.valueOf(s.trim()).floatValue();
System.out.println("float f = " + f);
}
catch (NumberFormatException e) {
System.out.println("NumberFormatException: " + e.getMessage());
}
}
}
// Output :float f = 100.0
There is nothing wrong with your code.
Exception happend because String is not a Float and cannot be parsed. Most common mistake - , instead of .
You are correct syntactically. I think problem is in mLongs. It might contain some alphabetic character.
Related
This question already has answers here:
Best way to parseDouble with comma as decimal separator?
(10 answers)
Closed 7 years ago.
I have a string.
String value = "The value of this product: 13,45 USD";
I want it to be a double which should be like:
double actualprice=13,45;
Or should i use float, double is useless here? Sorry, i am not an expert.
So how can i transform this string to a number?
oh and i almost forgot, i've got a code, which makes it to "13,45" but it's still a String.
String price = "The price is: 13.45";
String s = price;
for(int b=0;b<s.length();b++){
if(s.charAt(b)=='.') {
System.out.print(",");
}
if(Character.isDigit(s.charAt(b))) {
System.out.print(s.charAt(b)+"");
}
}
This code will work. It will throw a NumberFormatException if the string formatted in different manner and number was not found.
double actualprice = Double.parseDouble(
value.replaceFirst("The value of this product: (\\d+),(\\d+) USD", "$1.$2"));
System.out.println(actualprice);
This may be helpful.
public class RegexTest1 {
public static void main(String[] args) {
Pattern p = Pattern.compile("\\d+,\\d+");
Matcher match = p.matcher("The value of this product: 13,45 USD");
Double d ;
while (match.find()) {
System.out.println(match.group());
DecimalFormat df = new DecimalFormat();
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator(',');
symbols.setGroupingSeparator(' ');
df.setDecimalFormatSymbols(symbols);
try {
d = (Double)df.parse(match.group());
System.out.println(d);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
I have a null value in my message or println that i want to delete, all succeed when i just using code like this.
the message before :
message = 2014-06-02 14:53:37.103 null tes
Here is the code that delete the null word.
public static void main(String[] args) {
//final int month = Integer.parseInt(period[0]), year = Integer.parseInt(period[1]);
Date x = new Date();
Timestamp t = new Timestamp(x.getTime());
String a = "null";
String b = t+" " +a + " tes";
String tes = (b.trim()!= null && b.trim().length()>=23) ? b.trim().replaceFirst(b.trim().substring(0,28), ""+t) : b;
System.out.println("message = " + tes);
}
The printout is right. its like this :
message = 2014-06-02 14:53:37.103 tes
But when i insert this | the printout gone wrong. i'm using that as a separator.
This is the code that went wrong.
public static void main(String[] args) {
//final int month = Integer.parseInt(period[0]), year = Integer.parseInt(period[1]);
Date x = new Date();
Timestamp t = new Timestamp(x.getTime());
String a = "null";
String b = t+"| " +a + " tes";
String tes = (b.trim()!= null && b.trim().length()>=23) ? b.trim().replaceFirst(b.trim().substring(0,28), ""+t) : b;
System.out.println("message = " + tes);
}
And this is the print out :
message = 2014-06-02 14:58:03.148| null tes
What happen to the second code actually?
Thanks
As Boris said there are other ways, but the main problem is that replaceFirst takes a regex and pipe is a special character in regex.
Below with the introduction of Pattern.quote the code should work:
b.trim().replaceFirst(Pattern.quote(b.trim().substring(0,28)), ""+t)
If you want to simply strip out the 'null' text string without the regEx issues above, and quickly and cleanly, just replace the 'null' String directly.
b.replace("null", "")
What is exactly the main purpose of the program? if it is just to remove the null in the String, I would do as JamasA says. Otherwise if you want to get the timestamp and the "tes" string in two clean strings I would do it in this way:
String tes = b.replace("null", "");
String[] aux = tes.split("\\|");
for (int i = 0; i < aux.length; i++) {
System.out.println(aux[i].trim());
}
In this way you get both information separated.I hope it will helpful for you :)
This is the code that i have written to get the text from the textboxes, parse them to double datatype, and print their product. So, is there any alternative for parsing a string to double with its exceptions handled..?
...........
public void actionPerformed(ActionEvent ae){
try{
if(ae.getSource()==b1 || ae.getSource()==t2){
String s1=t1.getText();
String s2=t2.getText();
double x=Double.parseDouble(s1);
double y=Double.parseDouble(s2);
double z=x*y;
t3.setText(""+z);
}
if(ae.getSource()==b2){
t1.setText(null);
t2.setText(null);
t3.setText(null);
t1.requestFocus(true);
}
}catch(NumberFormatException nfe){
JOptionPane.showMessageDialog(this,"Please Enter Proper Number in the TextFields");
}
}
...............
String s1 = t1.getText();
try {
double x = Double.parseDouble(s1);
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(this,"Please Enter Proper Number in the t1 TextField");
return;
}
String s2 = t2.getText();
try {
double y = Double.parseDouble(s2);
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(this,"Please Enter Proper Number in the t2 TextField");
return;
}
It is you who knows how to handle such exceptions in your case. There is no other ways around to get the exceptions handled for you. Your code is correct and that is what done by most programmers. You may use JFormattedTextField but however that also doesn't handle exceptions for you.
IMHO No,
If you see Docs
public static double parseDouble(String s)
throws NumberFormatException
even if any shortcut is there it will use the above method and apperently thats also throws the same exception.
To avoid handling exceptions while parsing strings to get numbers (or double, in your case), you can use NumberFormat in conjunction with ParsePosition as shown below:
import java.text.NumberFormat;
import java.text.ParsePosition;
public class TestClass
{
public static void main(String[] args)
{
System.out.println("Parse test 10.00 ---> " + parseNumber("10.00"));
System.out.println("Parse test \"\" ---> " + parseNumber(""));
System.out.println("Parse test 10 ---> " + parseNumber("10"));
System.out.println("Parse test shgdfhsaghdga ---> " + parseNumber("shgdfhsaghdga"));
}
private static boolean parseNumber(String input)
{
NumberFormat fmt = NumberFormat.getInstance();
ParsePosition pos = new ParsePosition(0);
fmt.parse(input, pos);
return input.length() != 0 && (input.length() == pos.getIndex());
}
}
OUTPUT
Parse test 10.00 ---> true
Parse test "" ---> false
Parse test 10 ---> true
Parse test shgdfhsaghdga ---> false
If the number is a valid string, the index of the ParsePosition object will reach the end of the string. Otherwise, it will end at the first invalid position. The last return statement checks this condition. You can use the parseNumber() method to prevalidate your string before parsing it to double.
I want to get binary (011001..) from a String but instead i get [B#addbf1 , there must be an easy transformation to do this but I don't see it.
public static String toBin(String info){
byte[] infoBin = null;
try {
infoBin = info.getBytes( "UTF-8" );
System.out.println("infoBin: "+infoBin);
}
catch (Exception e){
System.out.println(e.toString());
}
return infoBin.toString();
}
Here i get infoBin: [B#addbf1
and I would like infoBin: 01001...
Any help would be appreciated, thanks!
Only Integer has a method to convert to binary string representation check this out:
import java.io.UnsupportedEncodingException;
public class TestBin {
public static void main(String[] args) throws UnsupportedEncodingException {
byte[] infoBin = null;
infoBin = "this is plain text".getBytes("UTF-8");
for (byte b : infoBin) {
System.out.println("c:" + (char) b + "-> "
+ Integer.toBinaryString(b));
}
}
}
would print:
c:t-> 1110100
c:h-> 1101000
c:i-> 1101001
c:s-> 1110011
c: -> 100000
c:i-> 1101001
c:s-> 1110011
c: -> 100000
c:p-> 1110000
c:l-> 1101100
c:a-> 1100001
c:i-> 1101001
c:n-> 1101110
c: -> 100000
c:t-> 1110100
c:e-> 1100101
c:x-> 1111000
c:t-> 1110100
Padding:
String bin = Integer.toBinaryString(b);
if ( bin.length() < 8 )
bin = "0" + bin;
Arrays do not have a sensible toString override, so they use the default object notation.
Change your last line to
return Arrays.toString(infoBin);
and you'll get the expected output.
When you try to use + with an object in a string context the java compiler silently inserts a call to the toString() method.
In other words your statements look like
System.out.println("infobin: " + infoBin.toString())
which in this case is the one inherited from Object.
You will need to use a for-loop to pick out each byte from the byte array.
this must be quite simple but I am having great difficulty. You see I am trying to find a string within another string as follows.
e = input.indexOf("-->");
s = input.indexOf("<!--");
input = input.replace(input.substring(s, e + 3), " ");
The integers e and s are returning -1 in that it was not found and this is causing the replace method to fail. The test string I am using is "Chartered Certified<!--lol--> Accountants (ACCA)". I tried to creat a new string object and pass in the string as an argument as follows
e=input.indexOf(new String("<!--"));
This yielded the same result.
Any ideas ?
This is a stand alone piece of code I wrote and it works perfectly.
public static void main(String[] args) {
int e = 0;
int s = 0;
while (e != -1) {
//input.replace("\"", "\'");
e = input.indexOf("-->");
s = input.indexOf("<!--");
input = input.replace(input.substring(s, e + 3), " ");
e = input.indexOf("-->");
System.out.println(input);
}
}
But I cannot seem to see why it fails when i use this logic in my action class.
System.out.println("!Chartered Certified<!--lol--> Accountants (ACCA)".indexOf("-->"));
prints 27
So your input string must not be what you expect
String input = "Chartered Certified<!--lol--> Accountants (ACCA)";
int e = input.indexOf("-->");
int s = input.indexOf("<!--");
System.out.println(e+" "+s);
yields
26 19
so I think that there's an error somewhere else, is there other code in the middle?
The string "Chartered Certified Accountants (ACCA)" does not contain "-->" or "<!--", so e and s will always be -1.
Maybe you are obtaining the string from a sort of xml parser and hides the commented string on rendering. Check that the input string just before the indexOf call really has the '<!--' and '-->' strings inside.
I ran the test real quick using a command-line argument. It worked just fine. Here's the code/results:
public static void main(String[] args) {
String input = args[0];
System.out.println(input);
int e = input.indexOf("-->");
int s = input.indexOf("<!--");
input = input.replace(input.substring(s, e + 3), "");
System.out.println(input);
}
Output:
Chartered Certified<!--lol--> Accountants (ACCA)
Chartered Certified Accountants (ACCA)
If you were passing input as a command-line argument, make sure it is in quotes, or else input will be set to Chartered because of the spaces.
This code should work, there is some other problem. You should code it for safety though as shown below.
e = input.indexOf("-->");
s = input.indexOf("<!--");
if (e > -1 && s > -1 && e > s + 4) {
input = input.replace(input.substring(s, e + "-->".length()), " ");
}
Your code seems OK. So if it fails. it may be that the string it parses is not what you think it is. Where does the string come from? Try printing the string just before parsing it to see what it actually is.