字符串到整数错误

时间:2018-03-31 16:52:43

标签: java string integer

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {

public static void main(String[] args) {
    try {
        File f = new File("C:/Users/asus/IdeaProjects/whatt/src/food.txt");
        Scanner sc = new Scanner(f);

        List<Person> people = new ArrayList<Person>();

        while(sc.hasNextLine()){
            String line = sc.nextLine();
            String[] details = line.split("\t");
            int serial = Integer.parseInt(details[0]);
            String name = details[1];
            int age = Integer.parseInt(details[2]);
            Person p = new Person(serial, name, age);
            people.add(p);
        }

        for(Person p: people){
            System.out.println(p.toString());
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}
}
 class Person{

private int serial;
private String name;
private int age;

public Person(int serial, String name, int age){
    this.serial = serial;
    this.setName(name);
    this.age = age;
}


public int getserial() {
    return serial;
}


public void setserial(int serial) {
    this.serial = serial;
}


public void setName(String name) {
    this.name = name;
}


public String getName() {
    return name;
}


public int getAge() {
    return age;
}


public void setAge(int age) {
    this.age = age;
}

public String toString(){
    return this.serial + " " + this.name + " " + this.age;
}


}

1001 elma 87

1002 muz 98

1003鳄梨221

1004 blackberry 64

1005 armut 79

1006 ayva 91

1007 erik 65

我有这样的txt文件。它包含2个整数和1个字符串。我试图将这些字符串转换为整数但是&#34; 1001&#34;总是给java.lang.NumberFormatException错误。我该怎么做才能解决这个问题?

2 个答案:

答案 0 :(得分:0)

问题是String.split()需要正则表达式。所以它实际上并没有拆分标签。尝试创建参数\\t,以便转义反斜杠。这将允许正则表达式正确解析。

答案 1 :(得分:0)

不要依赖于\ t,\ n或\ r \ n,请尝试使用java Regex。这是提取数字的更好方法。

例如:(^[0-9]*)\\s*[Aa-zZ]*\\s*([0-9]*)

第一个(^[0-9]*)捕获第一个String 第二个([0-9]*)捕获第二个字符串

// String to be scanned to find the pattern.
  String line = "1001 elma 87";
  String pattern = "(^[0-9]*)\\s*[Aa-zZ]*\\s*([0-9]*)";

  // Create a Pattern object
  Pattern r = Pattern.compile(pattern);

  // Now create matcher object.
  Matcher m = r.matcher(line);
  if (m.find( )) {
      int first = Integer.parseInt(m.group(1));
      int second = Integer.parseInt(m.group(2));
     System.out.println("first int " + first );
     System.out.println("second int " +second);
  }

它会打印出来:

first int 1001
second int 87

这是正则表达式的用途:识别提取部分字符串