【问题标题】:how to split first and last name in string array in java如何在java中的字符串数组中拆分名字和姓氏
【发布时间】:2018-11-15 04:08:48
【问题描述】:

我有一个包含 15 个全名的数组,我如何将它分成 2 个数组(名字和姓氏)下面是我的全名数组的方法

public static void readData(String file) throws FileNotFoundException {
    x = new Scanner(new File(file));
    //count number of names in the array
    int n = 0;
    while(x.hasNextLine()) {
        n++;
        x.nextLine();
    }
    //open another scanner to avoid null
    Scanner x1 = new Scanner(new File(file));
    name = new String[n];
    //get the array and print 
    for(int i = 0; i < name.length; i++ ) 
        name[i] = x1.nextLine();
    System.out.println(Arrays.toString(name));
}   

【问题讨论】:

  • 创建两个数组。当您从文件中读取String 时,在分隔符上拆分,我假设这是一个“空格”,然后将每个元素添加到相应的数组中
  • 只是出于好奇,您为什么要打开“另一个扫描仪以避免空值”?似乎完全没有必要。
  • 你为什么要把它读入一个数组?只需一次拆分并打印。此外,您泄漏的不是一个而是两个文件句柄!
  • @Carcigenicate 查看代码,他们试图提前确定文件中的行数......他们需要将Scanner 重置为文件的开头,这就是为什么我假设他们使用了两个扫描仪,但也没有关闭……而且通常会弄得一团糟(我怀疑这会是 NPE)

标签: java arrays string split


【解决方案1】:

文件包含 15 个这样的全名:

Max Frei
Stephen King
Agatha Christie

如何阅读:

final int total = 15;
String[] firstNames = new String[total];
String[] lastNames = new String[total];

try (Scanner scan = new Scanner(new File("file"))) {
    for (int i = 0; i < total; i++) {
        firstNames[i] = scan.next();
        lastNames[i] = scan.next();
    }
}

// firstNames: Max, Stephen, Agatha
// lastNames: Frei, King, Christie

【讨论】:

  • 我还想确保我正确理解了这一点。关键是使用 scan,next() 而不是 nextLine()。当您执行 scan.next() 时,它会将第一个名称分配给 firstName,然后将下一个分配给 lastName,然后在 for-loop 中重复循环,因此在这种情况下,我的 String[] 名称实际上是无关紧要的。对吗?
  • nextLine() 读取整行,next() 读取直到下一个分隔符
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-11
  • 2020-12-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-04
  • 2015-12-21
相关资源
最近更新 更多