Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Problem to convert string to integer

Status
Not open for further replies.

volcano

Programmer
Aug 29, 2000
136
0
0
HK
Hello, I have a problem when converting a string to integer...would you do me a flavour to see what the problem is? (the program cant be compiled successfully)
---------------
import java.io.*;

public class TEST {

public static void main (String args[]) throws IOException {
if (args.length != 1)
{
System.out.println("Please supply the parameter for this program.");
System.exit(0);
}

FileReader fr = new FileReader(args[0]);
BufferedReader br = new BufferedReader(fr);
String line = null;
String s1 = null;
String newscontent = null;
int tmp_timestamp = 0;

while ((line = br.readLine()) != null) {
if (line.length() > 14 && line.substring(1, 1) != "#")
{
s1 = line.substring(line.length() - 14, line.length());
tmp_timestamp = Integer.parseInt(s1);
System.out.println(tmp_timestamp);
}
}

}
}
 
sorry, the program should be compiled successfully. But once I run it with the provided file, it caused an error :

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

indicates the problem - the input string is null - and hence is not convertible to a numeric.
 
thanks for your reply!

in my program, i have added a checking "while ((line = br.readLine()) != null)"; therefore the input string should not be null. And in my testing data, the input characters are all numbers. So I wondered why I got this error..
 
hello, I finally solve the problem...the story is that the input string is too long to assign to an integer. When i changed Integer to be Long, the program ran without errors. I am so careless. Anyway thanks for your attention!
 
i would suggest you use valueOf(), parse() has been depricated. see below...

int intSale = Integer.valueOf(txtSale.getText()).intValue();

mad2
 
This is the Sun code for valueOf(String s) :
Code:
public static Integer valueOf(String s) throws NumberFormatException {
  return new Integer(parseInt(s, 10));
}
And this is the Sun code for parseInt(String s) :
Code:
public static int parseInt(String s) throws NumberFormatException {
  return parseInt(s,10);
}
So , if you want an int, you can better use "parseInt(String s) to avoid converting from int to Integer and back to int"
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top