When I run the application, it returns error codes on the console. The problem is that I can't convert from string to int
on this line:
int ogrNo=Integer.parseInt(row[0]);
This is the method I'm using:
public void OgrDosyaRead() {
try {
File file = new File("D:\\dosya.txt");
BufferedReader buf = new BufferedReader(new FileReader(file));
String line = null;
while((line=buf.readLine())!= null) {
String[] row = line.split(",");
int No=Integer.parseInt(row[0]);
String Name=row[1];
String Surname=row[2];
String lesson1=row[3];
String lesson2=row[4];
put(No,Name,Surname,lesson1,lesson2);
}
buf.close();
}
catch (Exception error) {
error.printStackTrace();
}
}
public void put(int No,String Name,String Surname,String lesson1,Strşng lesson2) {
Error Message like this;
java.lang.NumberFormatException: For input string: "1"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at Ogrenciler.HashTable.OgrDosyaRead(HashTable.java:178)
at Ogrenciler.MainClass.main(MainClass.java:38)
My file, dosya.txt, looks like this:
1,Helen,Dobre,Lesson1,Lesson2
public static void main(final String[] args)
{
final String data = "1,Helen,Dobre,Lesson1,Lesson2";
final String[] row = data.split(",");
final int c1 = Integer.parseInt(row[0]);
System.out.println("c1 = " + c1);
}
c1 = 1
Your problem is something in your data, probably hidden whitespace characters of some some sort in the 1,
part of your line, or the file is encoded with a different encoding than the Java default.
System.out.println(String.format("%040x", new BigInteger(1, data.getBytes(Charset.defaultCharset()))));
This is what the output should be for the example you have given:
312c48656c656e2c446f6272652c4c6573736f6e312c4c6573736f6e32
If you get something different then most likely the file is not encoded with the same encoding that
Charset.defaultCharset()
is. You will have to find whatCharset
the file is actually encoded with, this depends on what application was used to create the.txt
file. If it was something Windows specific it is probably some Windows default encoding, which is not the Java default.
When I changed my code like this:
int ogrNo = Integer.parseInt(row[0].replaceAll("[^0-9]", ""));
It now works.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.