java - 有没有办法用空格分隔文件扫描仪,但将名字和姓氏用空格分隔为一个字符串?

标签 java string substring

我试图让扫描仪读取文件的行,并用空格分隔值,但也将名字和姓氏保留在一起作为一个字符串。

这是一个例子:

将其作为纯文本文件:

Rachael Adams 3.36 1.93
Foluke Akinradewo 4.81 1.14
Kayla Banwarth 2.98 0.5
Michelle Bartsch 0.28 1.42
Krista Vansant 2.78 0.86
Courtney Thompson 0.59 0.93
Kelly Murphy 1.15 0.58
Lauren Gibbemeyer 2.25 0.5
Alexis Crimes 3.89 1.34
Tori Dixon 0.92 1.62
Nicole Fawcett 4.01 0.61
Alisha Glass 1.96 1.55
Natalie Hagglund 2.49 0.52
Kim Hill 1.53 1.76
Cursty Jackson 0.69 1.44

我需要能够单独对每个字段进行排序,如下所示:

String s = "Kim Hill";
double d1 = 1.53;
double d2 = 1.76;

这样我就可以将它们传递到每个 Person 对象的构造函数中。
这是我尝试过的:

    Roster(String fileName) throws FileNotFoundException {
    File rosterFile = new File(fileName);
    Scanner fileScanner = new Scanner(rosterFile);

    while (fileScanner.hasNextLine()) {
        String lineString = fileScanner.nextLine();
        String name = lineString.substring(0, lineString.length() - 10);
        Double attack = Double.valueOf(lineString.substring(lineString.length() - 9, lineString.length() - 5));
        Double defense = Double.valueOf(lineString.substring(lineString.length() - 5));
        peopleArrayList.add(new Person(name, attack, defense));
    }
    sizeOfRoster = peopleArrayList.size();
    fileScanner.close();
}

我遇到的问题是,某些行在评估数据中包含 0.5 而不是 0.50,因此我的 lineString.length 在这里不适用。我的训练数据有额外的数字,所以现在我必须弄清楚如何以不同的方式做到这一点。

最佳答案

试试这个:

public static void main (String[] args) {
        String name = null;
        double attack = 0, defense = 0;
        try {
            Scanner s = new Scanner(new File("file.txt"));
            while(s.hasNext()) {
                name = s.next() + " "+ s.next();
                attack = s.nextDouble();
                defense = s.nextDouble(); 

                peopleArrayList.add(new Person(name, attack, defense));

                System.out.println();
                System.out.println(name);
                System.out.println(attack);
                System.out.println(defense);
            }
            s.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

输出:

Rachael Adams
3.36
1.93

Foluke Akinradewo
4.81
1.14

Kayla Banwarth
2.98
0.5

Michelle Bartsch
0.28
1.42

Krista Vansant
2.78
0.86

Courtney Thompson
0.59
0.93

Kelly Murphy
1.15
0.58

Lauren Gibbemeyer
2.25
0.5

Alexis Crimes
3.89
1.34

Tori Dixon
0.92
1.62

Nicole Fawcett
4.01
0.61

Alisha Glass
1.96
1.55

Natalie Hagglund
2.49
0.52

Kim Hill
1.53
1.76

Cursty Jackson
0.69
1.44

关于java - 有没有办法用空格分隔文件扫描仪,但将名字和姓氏用空格分隔为一个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59130466/

相关文章:

java - RxJava2 批处理项

Java 替换全部

c - 是否有一种优雅的行业标准方式在 C 中实现 substr ?

java - 这是内存泄漏还是我刚刚达到了内存中可以保留的对象的限制?

python - 在Python中从字符串中提取正确的字符

java - 如何调用 PaintComponent 方法?

java - Jersey servlet 的 web.xml 不响应请求

java - Android 上的 ARCore 是否支持像 ARKit 一样的实时反射?

python - 如何计算 Pandas 数据框的大写和小写

python - 函数返回 None 而不是预期的字符串