java substring returning empty - java

I'm attempting to take a substring of a string txt and then set another portion of that string to a value, however whenever I try to set voltage[t] with the double value of the substring, I'm getting an empty string error. Here's the part of the code where I'm getting the error:
if(txt.substring(0,1).equals("1")) {
//Voltage button pressed(S3)
//=====================================================================
text3.setText(txt.substring(1));
voltage[t] = (Double.parseDouble(text3.getText()));
}
Anyone know why this error would be occurring? Any help would be appreciated. Thanks!
Edit:
Here is the exact exception I'm receiving:
Caused by: java.lang.NumberFormatException: empty String
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
at sun.misc.FloatingDecimal.parseDouble(Unknown Source)
at java.lang.Double.parseDouble(Unknown Source)
at UartApp$11.run(UartApp.java:728)
at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35)
at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:135)
The error occurs on line 728
Also, here's the code I'm using to convert the int and adding the "1". The microcontroller is programmed in C:
char *p, text[32];
int i = readADC(POT);
sprintf(text,"1%d", i);
p = text;
UartTxString(p); //Sends string out

If the code you provided is complete and representable, then Double.parseDouble(...) would throw an exception indicating an empty string if and only if txt is the string "1" (and nothing else).
Assuming you want to get the double value of "1", then the way you would fix this is by changing text3.setText(txt.substring(1)); to text3.setText(txt.substring(0,1));.
If instead what you want to do is to get the double value of anything in the string after the leading "1", then I think you may have a problem elsewhere in your code--wherever it is that you set the value of txt. If so, could you post that code as well so that we can take a look?
(I think what may be happening is that you intended to prepend "1" to txt, but instead accidentally replaced the value of txt with "1" entirely)
EDIT:
The problem may be with text3 instead.
Try this. Replace
voltage[t] = (Double.parseDouble(text3.getText()));
with
voltage[t] = (Double.parseDouble(txt.substring(1)));
EDIT #2:
If the above replacement did not fix the problem, then it must be true that txt is exactly the string "1" (and nothing else) within this scope. The problem may lie in how you are prepending the '1' to txt.

Related

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 Parsefloat Exception with a string that is number followed by characters

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.]

Error in Spliting and Concatenating String

I am trying to make query by performing operation on String. I have a String named query like this:
2010-10-01' and '2013-10-01' and (extension='5028' or extension='00' or extension='
Now with the following code I am deleting last 16 characters from query string. Here is the code:
query=query.substring(0,query.length()-16);
output of this snippet is:
2010-10-01' and '2013-10-01' and (extension='5028' or extension='00
Now I want to concatenate the string with this character:
query=query.concat("')");
output of above snippet is
2010-10-01' and '2013-10-01' and (extension='5028' or extension='00)'
Whereas I need the output like this:
2010-10-01' and '2013-10-01' and (extension='5028' or extension='00')
I hope I don't get downvoted since I don't have time to check this right now but it looks to me like you're in the single-quote/double quote character vs string mess. I'm a little surprised it compiled. I'd try:
query=query.concat("\')");

NumberFormatException error (parseInt)

Hopefully a very simple query, but it's left me scratching my head.
I have a string, which is just a single integer, and I'm trying to then get that integer out as an int. This on the face of it shouldn't be a problem.
// this is how I create the string (it's the playload from a UDP datagram packet,
// thought I don't think the origins hugely important - it's juts a test run so the
// stringMessage is always 1 (created by a seperate client process)
...
recvSoc.receive(pac);
String stringMessage = new String(pac.getData());
port = pac.getPort();
System.out.println("RECEIVED: " + stringMessage + " on port: " + port);
processMessage(stringMessage);
...
// Then in processMessage
public void processMessage(String data) {
int message;
message = Integer.parseInt(data);
...
This always crashes with a NumberFormatException error. I cannot for the life of me figure out what's causing this, any ideas greatly appreciated. I haven't coded much in Java (recently) so might simply be forgetting something critical or what not.
Exception in thread "main" java.lang.NumberFormatException: For input string: "1"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:481)
at java.lang.Integer.parseInt(Integer.java:514)
at udp.UDPServer.processMessage(UDPServer.java:85)
at udp.UDPServer.run(UDPServer.java:52)
at udp.UDPServer.main(UDPServer.java:156)
If the string is really 1, the exception can't happen. So I would say the string is not actually 1.
do a data.toCharArray() and print each character's code (cast to int). It may turn out that there is a hidden character before the digit, for example. (edit: it appears iluxa mentioned this option in a comment while I was writing the answer)
Try data = data.trim() before passing it to parseInt(..)
Note that DatagramPackate.getData() returns the whole buffer!
The data you received is only a part of it:
The data received or the data to be sent starts from the offset in the buffer, and runs for length long.
So to convert the data to a String you should use this constructor:
String message = new String(pac.getData(), pac.getOffset(), pac.getLength(), "UTF-8");
Note that I specify the UTF-8 encoding here, as not specifying an encoding would result in the platform default encoding to be used, which is generally not what you want.

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