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.
Related
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.
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.
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 ...)
I am getting stuck in a basic JSP Operation. I want to a new line so i have added \n in the end but it throws me an exception. If i remove \n everything works fine
Exception
java.lang.IllegalArgumentException: Invalid LF not followed by whitespace
Class File
StringBuilder junitLog = new StringBuilder();
junitLog.append("The class that is being executed : " + description.getClassName() +"\n");
junitLog.append("Number of testcases to execute : " + description.testCount()+"\n");
/**
* #return the junitLog
*/
public StringBuilder getJunitLog() {
return junitLog;
}
/**
* #param junitLog the junitLog to set
*/
public void setJunitLog(StringBuilder junitLog) {
this.junitLog = junitLog;
}
JSP:-
response.setHeader("finalJUNITReport",""+ junitListener.getJunitLog());
try Base64 encoding them before you set in headers and Base64 decoding them when you want to read them back.
As long as you think to it in the OO way, you can wonder why you couldn't put new line in your headers.
But as soon as you think that it will be transmitted using HTTP protocol, it becomes evident : a HTTP message (request or response) is nothing else than a sequential serie of bytes. For HTTP, the header section comes first and is composed of lines like that :
HEADER_NAME: header value
If you put a new line in a header value, anything that would follow would be considered as a new header. And if you put 2 consecutive new lines that would denote the end of the header section.
All you can do is to use "\n ", because a line beginning with a space if supposed to be a continuation line.
That's the reason of the error message Invalid LF not followed by whitespace, and hopefully it was there, because you would have send an incorrect header section what could be harder to detect ...
I howeva suceeded in my requirement. :)
As clearly stated by Serge Ballesta.
If you put a new line in a header value, anything that would follow would be considered as a new header..
So below is the logic i applied based on my requirement.
Below were my code changes:
junitLog.append("The class that is being executed : " + description.getClassName() +"?");
junitLog.append("Number of testcases to execute : " + description.testCount()+"?");
I added a question mark at the end of the string. THe string became something as mentioned below.
The class that is being executed : testCreateHaulier? Number of testcases to execute : 39?
I passed the String from JSP using response.setHeader Code as below:
response.setHeader("finalJUNITReport",""+ junitListener.getJunitLog());
and in my java class file i did something like this:
junitReportString=yc.getHeaderField("finalJUNITReport").toString();
System.out.println(junitReportString);
junitReportString=junitReportString.replaceAll("\\?", "\n");
System.out.println("Report Details ==============>"+junitReportString);
Using replaceAll i replaced all question marks to new line and my requirement was done.
Hope it helps others too.:)
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?