I try to convert int String to int
int port = Integer.parseInt(tokens[2]);
tokens[2] contain a String "12777"
But I got this error
Exception in thread "Thread-2019" java.lang.NumberFormatException: For
input string:
"12777"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:458)
at java.lang.Integer.parseInt(Integer.java:499)
at inet.ChildServer.hopen(ChildServer.java:88)
at inet.ChildServer.run(ChildServer.java:51)
Edit: Sorry the characters are invisible in eclipse, I don't Understand what is this.
I have a String in this form
command1|Destination-IP|DestinationPort
and I just splot it
String[] tokens = sentence.split( "[|]" );
can you trim the string before pass to Integer.parseInt(tokens[2]); it may contain blank spaces.
As have guys already mentioned your string does not contain 12777 as you think. It contains 12777 and then a lot of garbage that prevents parsing of your string to int. Debug your code to understand what is the source of this garbage. Take a look on code that assigns value to tokens[2].
If you have problems there post the code that assigns value to tokens[2].
Good luck.
EDIT
OK, you have posted yet another part of your code. But the problems seems to be before this point. Take a look on code that assigns value to sentence.
BTW: you can see everything in eclipse. Expand the string and see the character array stored into the string.
Be careful you can have errors after you
String x = "123";
Integer.parseInt(x);
do
String x = "jonas";
try{
Integer.parseInt(x.trim());
catch(NumberFormatException e){
//do something creative with the error
}
Related
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class MainProgram {
public static void main(String[] args ) throws IOException{
String seconds = " ";
Scanner sc2 = null;
try {
sc2 = new Scanner(new File("/Users/mohammadmuntasir/Downloads/customersfile.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
boolean first = true;
while (sc2.hasNextLine()) {
Scanner s2 = new Scanner(sc2.nextLine());
while (s2.hasNext()) {
String s = s2.next();
if (first == true){
seconds = s;
first = false;
}
}
}
System.out.println(Integer.parseInt(seconds)); // causes ERROR?
}
}
I am trying to read a number from a text file which is in the first line by itself. I made an integer called seconds that will take in the first number and will be parsed into an integer. But I always get a numbers exception error and that I can't parse it. When I display s as a string, it displays a number without spaces next to it. Can anyone explain why this happens?
Here is the stacktrace:
Exception in thread "main" java.lang.NumberFormatException: For input string: "300"
at java.lang.NumberFormatException.forInputString(NumberFormatE‌xception.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at MainProgram.main(MainProgram.java:29)
If the exception message is really this:
java.lang.NumberFormatException: For input string: "300"
then we are starting to get into really obscure causes.
It could be a problem with homoglyphs; i.e. Unicode characters that look like one character but are actually different characters.
It could be a non-printing character. For example an ASCII NUL ... or a Unicode BOM (Byte Order Marker) character.
I can think of three ways to diagnose this:
Run your code in a debugger and set a breakpoint on the parseInt method. Then look at the String object that you are trying to parse, checking its length (say N) and the first N char values in the character array.
Use a file tool to examine the file as bytes. (On UNIX / Linux / MacOSX, use the od command.)
Add some code to get the string as an array of characters. For each array entry, cast the char to an int and print the resulting number.
All three ways should tell you exactly what the characters in the string are, and that should explain why parseInt thinks they are wrong.
Another possibility is that you copied the exception message incorrectly. The stacktrace was a bit mangled by the time you got it into the Question ...
Have a look at your input file with a hex-editor. It might start with some "strange" hex codes called Byte Order Markers. This would explain why the Exception is so misleading becaus BOMs won't be shown on the console.
can you try this, I had the same probleme , Integer.ParseInt(String) didn't work for me, I added .trim() and it works perfectly:
int id_of_command;
try {
id_of_command = Integer.parseInt(id_of_Commands_str.trim());
}
catch (NumberFormatException e)
{
id_of_command = 0;
}
If you are sure you are reading an integer, you can use seconds.trim() to trim any spaces and parse it.
If you are trying to parse space then it would cause an issue. Please check what value of seconds you are trying to parse.
Exception in thread "main" java.lang.NumberFormatException: For input string: " "
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:569)
at java.lang.Integer.parseInt(Integer.java:615)
at HelloWorld.main(HelloWorld.java:22)
Additionally try catching the exception and printing the value which is causing it. Something like this:
try{
System.out.println(Integer.parseInt(seconds));
}
catch(Exception e){
System.out.println("String value: '" + seconds + "'");
}
Can you update the question with stack-trace. Not sure what are the contents in your file.
Is it possible to append your code with something like this and put out your answer :
StringBuilder sb = new StringBuilder();
for (char c : seconds.toCharArray())
{
sb.append((int)c).append(",");
}
System.out.println(sb);
Your string can be empty or you string may contain space. So use trim & then parse.
Right now, I am making a simple tic-tac-toe project. I would like to know what happens to the integer i when:
string s = "hello"; //or something else, non integer
int i = Integer.parseInt(s);
What will i be equal to?
Integer.parseInt("hello") statement will throw an exception: java.lang.NumberFormatException
If the given string does not contain a parseable integer, a
NumberFormatException will be thrown.
For more information, see: https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt%28java.lang.String%29
Following is a small section of the code I am using, along with the syntax of the text file I am using. (I am fairly sure both are grossly overcomplicated, but I am not exactly sure how to simplify them.)
while((line = bufferedReader.readLine()) != null)
{
if(line.split("##")[0].equals(lineNumber))
{
numberOfLines = Integer.parseInt(line.split("##")[1]);
spaceSkip = 1;
worked = 0;
}
if(spaceSkip == 0)
{
if(numberOfLines > 0)
{
System.out.println(line);
numberOfLines--;
}
}
spaceSkip = 0;
}
And the format of the text file is:
1##2##3##0
Text goes below it,
and can span multiple lines.
The 3 and 0 do not come into play here. The intent is for the program to search for the number selected and match it to the first number, 1 in this case. The second number is the number of lines to read. In the code, I have "spaceSkip" so that it does not read the indexing line.
Explanations aside, the issue I am having is that line.split("##")[0].equals(lineNumber) seems to be reading false. I have printed both out to the screen at the same time, and both equal 1, but it is still returning an error message I included. ("worked = 0;" is what keeps the error from triggering.) I am certain it is a stupidly simple mistake I am making here, but I still am unable to figure it out. Thank you in advance.
Whenever a comparison doesn't return what you think it should, check that the types are what you think they are.
String#split returns an array of Strings. For your given input the first element of that array will be "1". If lineNumber is something other than a String, say an int, then equals will still work (the primitive int gets autoboxed to a java.lang.Integer, which is a subclass of java.lang.Object, which is the type the equals method takes as a parameter), but the comparison ("1".equals(1)) will always return false. JavaScript is OK with equating a string and an int ("1" == 1 returns true), but Java is not.
The easiest fix would be to convert the lineNumber to a String, by calling String#valueOf passing in lineNumber. It would be better to convert lineNumber to a String than try to convert the split output to an Integer, because the Integer parsing could fail on bad input, and I'd rather avoid having to manage that possibility.
The cut-n-pasting of the split call is unfortunate mostly because of redundancy, you should do the split once into a local variable like:
String[] parts = line.split("##");
if (parts[0].equals("1")) {
numberOfLines = Integer.parseInt(parts[1]);
...
Without seeing the initialization of the variables it is hard to tell, but it is possible that you are comparing a String to an Integer in this if statement.
You may want to try casting the second argument to a String as follows.
if(line.split("##")[0].equals(String.valueOf(lineNumber)))
Say I have a string,
String templatePhrase = "I have a string that needs changing";
I also have a method to replace words in any given String. Here is the method:
public String replace(String templatePhrase, String token, String wordToPut) {
return templatePhrase.replace(token, wordToPut);
}
Now say (for the sake of my actual task) I have all the words in my String str in a List named wordsInHashtags. I want to loop through all the words in wordsInHashtags and replace them with words from another List named replacement using the replace() method. Each time the loop iterates, the modified String should be saved so it will hold its replacement(s) for the next loop.
I will post my code if anyone would like to see it, but I think it would confuse more than help, and all I am interested in is a way to save the modified String for use in the next iteration of the loop.
I was just reading about strings in beginning Java 2 the other day, :"Strings Objects are immutable" Cant be changes basically however StringBuffer Objects were created to deal with such a circumstance as i understand it. You could try:
StringBuffer templatePhrase = "I have a string to be changed";
templatePhrase.replace(token, wordToPut);
String replacedString = (String)templatePhrase;
Line 3 may cause a problem?
public class Rephrase {
public static void main(String[] args) {
/***
Here is some code that might help to change word in string. originally this is a Question from Absolute Java 5th edition. It will change two variable whatever you want but algorithm never change.So the input from keyboard or any other input source.
********/
String sentence = "I hate you";
String replaceWord = " hate";
String replacementWord = "love";
int hateIndex = sentence.indexOf(replaceWord);
String fixed = sentence.substring(0,hateIndex)+" "+replacementWord+sentence.substring(hateIndex+replaceWord.length());
System.out.println(fixed);
}
}
So in Java, I know that str.endsWith(suffix) tests if str ends with something. Let's say I have a text with the line "You are old" in it. How would I take the "old" and set it as a variable so I can print it out in the console?
I know I could do:
if(str.endsWith("old")){
String age = "old";
}
But then I'm going to have more options, so then I'd have to do:
if(str.endsWith("option1")){
String age = "option1";
}
if(str.endsWith("option2")){
String age = "option2";
}
...
Is there a more efficient and less verbose way to check the end of strings over writing many, possibly hundreds, of if statements
Format:
setting: option
setting2: option2
setting3: option3 ...
Regardless of what "option" is, I want to set it to a variable.
If you are working with sentences and you want to get the word, do
String word = str.substring(str.lastIndexOf(" "));
You may need a +1 after the lastIndexOf() to leave the space out.
Is that what you are looking for?
Open your file and read the line with the readLine() method. Then to get the last word of the string you can do as it is suggested here
You mean like:
String phrase = "old";
if(str.endsWith(old)){
Is this what you're looking for?
List<String> suffixes = new ArrayList<String>();
suffixes.add("old");
suffixes.add("young");
for(String s: suffixes)
{
if (str.endsWith(s))
{
String age = s;
// .... more of your code here...
}
}
If you're worried about repeating very similar code, the answer is always (99%) to create a function,
So in your case, you could do the following:
public void myNewFunction(String this, String that){
if(this.endsWith(that)){
String this = that;
}
}
...
String str = "age: old";
myNewFunction(str, "old"); //Will change str
myNewFunction(str, "new"); //Will NOT change str
And if that is too much, you can create a class which will do all of this for you. Inside the class, you can keep track of a list of keywords. Then, create a method which will compare a given word with each keyword. That way, you can call the same function on a number of strings, with no additional parameters.
You could use this Java code to solve your problem:
String suffix = "old";
if(str.endsWith(suffix)) {
System.out.println(suffix);
}