2
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)
15
  • 1
    But I always get a numbers exception error Commented Apr 21, 2017 at 6:40
  • 4
    If your while loop stuff does not entered into then seconds will remain as " " which of course is not a number. Try debugging it Commented Apr 21, 2017 at 6:41
  • 1
    a tiny hint: the Exception (Stacktrace) actually tells you EXACTLY what you are trying to parse. From there on it should be rather trivial to identify WHY this doesn´t work (well if so it´s not a number you´re trying to parse) Commented Apr 21, 2017 at 6:41
  • 1
    Your string may be empty or you string may contain space. So use trim & then parse. Commented Apr 21, 2017 at 6:43
  • 2
    @Dankmemer it´s written inside the console whenever you execute it. Commented Apr 21, 2017 at 6:48

7 Answers 7

6

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:

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

  2. Use a file tool to examine the file as bytes. (On UNIX / Linux / MacOSX, use the od command.)

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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;
            }

Comments

-1

If you are sure you are reading an integer, you can use seconds.trim() to trim any spaces and parse it.

4 Comments

I am sure seconds is an integer. And seconds.trim() doesnt help :/
@Dankmemer - well we are equally sure that you are wrong about that! However if you were paying attention, you would have seen our repeated requests for you to post the full stacktrace ... which would clear up any possible doubt as to what you are actually parsing here.
NumberFormatException is thrown only if seconds does not contain parseable ineteger. Please see docs.oracle.com/javase/7/docs/api/java/lang/…
@OTM This can be better placed under comments section and not in "Answers" section.
-1

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.

8 Comments

'Exception in thread "main" java.lang.NumberFormatException: For input string: "300" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:580) at java.lang.Integer.parseInt(Integer.java:615) at MainProgram.main(MainProgram.java:29)'
@Dankmemer edit it into the question so people are able to read it (it´s pretty unreadable in the comment section)
Could be homoglyphs
@StephenC: Then would be interested to see what's there in that file.
Could also be non-printing characters ... of various kinds.
|
-1

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);

Comments

-2

Your string can be empty or you string may contain space. So use trim & then parse.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.