0

I need to enter a random amount of numbers from 0-500, once the return is an empty string, I need to exit the loop and do some calculations with the inputs. Here's my code so far:

String test = "";

while(test != null ){
    String[] inputs = br.readLine().split("\\s+");
    inputs[0] = test;

    if (test != null){
        inputs2[i] = Integer.parseInt(inputs[0]);
        StatsPackage.inputs[i] = Integer.parseInt(inputs[0]);
    }
    i++; 
}//end of while loop

Here is the error I keep getting:

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

at java.lang.NumberFormatException.forInputString(Unknown Source)

at java.lang.Integer.parseInt(Unknown Source)

at java.lang.Integer.parseInt(Unknown Source)

at StatsPackage.main(StatsPackage.java:84)

Line 84 is this:

inputs2[i] = Integer.parseInt(inputs[0]);

any ideas?

Jongware
  • 22,200
  • 8
  • 54
  • 100
  • `Integer.parseInt("");` this is what you are doing you will always get exception for that because `test` never changed – singhakash Oct 26 '15 at 19:25
  • 2
    Check [Difference between null and empty (“”) Java String](http://stackoverflow.com/questions/4802015/difference-between-null-and-empty-java-string) – sam Oct 26 '15 at 19:27
  • 1
    I'd like to understand the intent of your code, as the fact that you didn't understand the difference between `empty` and `null`, plus the use of `inputs2` variable, is leading me to believe there are much better design options that you're still unaware of as a beginner (?), and that would make your code much better. – CosmicGiant Oct 26 '15 at 20:00
  • Can you provide some sample data? Specifically, what is the value of `test`? – Makoto Oct 26 '15 at 20:42

2 Answers2

-2

You could verify if the string is not empty adding:

String test = "";

while(test != null && !test.isEmpty()){
String[] inputs = br.readLine().split("\\s+");
inputs[0] = test;

if (test != null){
    inputs2[i] = Integer.parseInt(inputs[0]);
    StatsPackage.inputs[i] = Integer.parseInt(inputs[0]);
}
i++; 
}//end of while loop
-2

Just try the following comparison in your code:

(test != null || !(test.equals("")))

In this case, you are avoiding NULL references and empty strings ("").

Hope this answer is helpful!

  • The check for empty doesn't need to be wrapped in a second parenthesis, and it would be better to use `String.isEmpty()` instead. Also, this doesn't really answer what's wrong with his code, and doesn't explicitly teach anything. I don't want to discourage you; but you're providing a solution here, not an answer. – CosmicGiant Oct 26 '15 at 20:04
  • Respectfully i say: He is requesting any idea to solve the issue, so this is a solution. I only tried to provide a solution of many that can be possible in this case. Likewise, i agree with you in the use of {String.isEmpty()} – Francisco Guevara Oct 27 '15 at 17:51