-2

Hello everyone i am new to java and i have a problem. I accept a number with the String type, then I write it to the txt variable, then I overwrite it and add "\n", and then I try to convert it to the int type, but no matter what number is, it always turns out to be zero.

        BufferedReader in = new BufferedReader(new InputStreamReader(clientConn.getInputStream()));     
        String txt = in.readLine();          
        txt = txt + "\n";                
        int number = Integer.parseInt(txt);

If I try to run a separate class that contains these lines of code, an error is thrown.

Exception in thread "main" java.lang.NumberFormatException: For input string: "1 "

and so with any number that I send.Always swears at the line int number = Integer.parseInt(txt);. Tell me how to solve this problem.

Viktor
  • 3
  • 2
  • 1
    Why do you append a `\n` to your number? – tkausl Nov 22 '21 at 03:33
  • The fact is that only when moving to the next line, I can again read the incoming data, since this piece of code is in a loop and receives numbers from the TCP client. – Viktor Nov 22 '21 at 03:47
  • 1
    But what does that have to do with doing `txt = txt + "\n"`? Try getting rid of that line of code. – Slaw Nov 22 '21 at 03:58
  • If `txt = txt +" \ n "` is left in the code, then after executing the line `int number = Integer.parseInt (txt);`, the value of number is passed to another class, and if I remove `txt = txt +" \ n "`, then the loop just accepts the data, but does not pass it to another class. – Viktor Nov 22 '21 at 04:09
  • Your last comment makes no sense. – Basil Bourque Nov 22 '21 at 06:23

1 Answers1

0

You pass invalid input

As the comments indicate, you add a newline to the text being parsed as an integer, thereby adulterating the input:

txt = txt + "\n";  

So you are violating the contract of Integer.parse method. To quote the Javadoc:

… The characters in the string must all be decimal digits…

Your attempt at parsing is throwing an NumberFormatException because you passed faulty input to that method.

int good = Integer.parseInt( "42" ) ;
int bad = Integer.parseInt( "666" + "\n" ) ; // Throws a `NumberFormatException` because of the appended newline.

See that code run live at IdeOne.com.

You asked:

Tell me how to solve this problem.

Pass valid input to the method, as documented: Text with only digits, and optional -/+ in front.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154