日期:2014-05-20  浏览次数:20739 次

字符串向整形的转换错误
Java code

private User parseUser(String row) {
    String[] data = row.split(":");
    User user = new User();
    try {
        System.out.println("data[0]" + data[0]);
        user.setId(Integer.parseInt(data[0]));
        user.setName(data[1]);
        user.setPasswd(data[2]);
        user.setPhone(data[3]);
        user.setEmail(data[4]);
    } catch (NumberFormatException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return user;
  }

Java code

data[0]?1000
java.lang.NumberFormatException: For input string: "?1000"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
    at java.lang.Integer.parseInt(Integer.java:447)
    at java.lang.Integer.parseInt(Integer.java:497)
    at com.lwx.elts.entity.EntityContext.parseUser(EntityContext.java:53)
    at com.lwx.elts.entity.EntityContext.loadUsers(EntityContext.java:38)
    at com.lwx.elts.entity.EntityContext.<init>(EntityContext.java:23)
    at com.lwx.elts.client.Main.main(Main.java:15)


为什么data[0]已经读出来是1000了 转换成整形还是会出错?



------解决方案--------------------

------解决方案--------------------
Java code

public class test {
    public static void main(String[] rags){
        parseUser("1000:csdn");
    }
    private static User parseUser(String row) {
        String[] data = row.split(":");
        User user = new User();
        try {
            System.out.println("data[0]:" + data[0]);
            user.setId(Integer.parseInt(data[0]));
            System.out.println("id:" + user.id);
            user.setName(data[1]);
        } catch (NumberFormatException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return user;
      }
    
}

class User{
    int id;
    String name;
    public void setId(int id){
        this.id = id;
    }
    public int getId(){
        return this.id;
    }
    public void setName(String name){
        this.name = name;
    }
}